【发布时间】:2017-03-01 23:05:23
【问题描述】:
我正在使用 Java Rest 客户端进行弹性搜索 https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/index.html 但找不到批量插入或更新的方法。如何批量操作此客户端?
【问题讨论】:
标签: java elasticsearch elasticsearch-java-api
我正在使用 Java Rest 客户端进行弹性搜索 https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/index.html 但找不到批量插入或更新的方法。如何批量操作此客户端?
【问题讨论】:
标签: java elasticsearch elasticsearch-java-api
用于 Elasticsearch 的 5.2 Java Rest 客户端是基于字符串的,并且很快就会变得混乱。对于批量操作尤其如此,因为它们是通过链接 JSON 对象构建的。
如果您想/必须通过 REST 客户端连接到您的 Elasticsearch 集群,我建议改用 JEST client。
这是一个关于如何使用 JEST 客户端处理批量请求的示例:
// Construct a new Jest client according to configuration via factory
JestClientFactory factory = new JestClientFactory();
factory.setHttpClientConfig(new HttpClientConfig
.Builder("http://localhost:9200")
.multiThreaded(true)
.build());
JestClient client = factory.getObject();
// Construct Bulk request from articles
Bulk bulk = new Bulk.Builder()
.defaultIndex("twitter")
.defaultType("tweet")
.addAction(Arrays.asList(
new Index.Builder(article1).build(),
new Index.Builder(article2).build()))
.build();
client.execute(bulk);
【讨论】:
如果您使用 Java 来处理 Elasticsearch Server,我建议您改用 Java API。这里是你可以拿的地方:https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/index.html
您可以在 Document API/Bulk API 中找到如何进行批量操作。
如果您出于某种原因仍需要使用 Java Rest 客户端,则需要构建 Elasticsearch 的批量请求格式的有效负载才能执行请求。
请在此处了解如何构建批量请求格式: https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html (基本上,它是由 json 对象列表构造的)
【讨论】:
我正在使用来自.json 文件的数据。
Elasticsearch 版本: 6.8.0
pom.xml:
<dependencies>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>6.8.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>6.8.0</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.1</version>
<scope>test</scope>
</dependency>
</dependencies>`
Java
String bulkContent = new String(Files.readAllBytes(new File(filePath).toPath()));
HttpEntity entity = new NStringEntity(bulkContent, ContentType.APPLICATION_JSON);
Request request = createRequest(indexName, indexType, httpMethod, entity);
RestClient restClient = RestClient.builder(new HttpHost(hostname, port, scheme)).build();
Response response = restClient.performRequest(request);
【讨论】: