java接入es的完整代码
时间: 2023-07-09 21:34:20 浏览: 15
这是一个简单的Java代码示例,用于连接Elasticsearch并索引一些数据:
```java
import java.io.IOException;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.rest.RestStatus;
public class ElasticsearchExample {
public static void main(String[] args) throws IOException {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
try {
// 构建要索引的文档内容
XContentBuilder builder = XContentFactory.jsonBuilder();
builder.startObject();
{
builder.field("title", "Java编程入门");
builder.field("author", "张三");
builder.field("price", 29.99);
builder.field("description", "一本入门级Java编程教程");
}
builder.endObject();
// 创建索引请求
IndexRequest request = new IndexRequest("books");
request.source(builder);
// 发送索引请求
RestStatus status = client.index(request, RequestOptions.DEFAULT).status();
if (status == RestStatus.CREATED) {
System.out.println("文档已成功索引!");
} else {
System.out.println("文档索引失败!");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭客户端连接
client.close();
}
}
}
```
这个示例连接到本地运行的Elasticsearch实例,索引一本书的信息。注意:在运行此代码之前,请确保你已经安装并启动了Elasticsearch,并且已经在Elasticsearch中创建了名为“books”的索引。
相关推荐
















