赞
踩
1.引入依赖,这里使用的是es的7以上的版本,使用elasticsearch-rest-high-level-client 高级别API来创建客户端
<!-- https://mvnrepository.com/artifact/org.elasticsearch/elasticsearch -->
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.3.1</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.3.1</version>
</dependency>
2.批量请求更新的Demo
package cn.sse;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class ElasticSearchBulkOpreation {
public static void main(String[] args) throws IOException {
//当es用用户名和密码连接时
//初始化ES操作客户端
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials("elastic", "123456")); //es账号密码(默认用户名为elastic)
RestHighLevelClient client =new RestHighLevelClient(
RestClient.builder(new HttpHost("192.168.6.1",9200,"http")).setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
httpClientBuilder.disableAuthCaching();
return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
})
);
当es无密码时可以直接使用下面这个创建客户端
//RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost(
// "192.168.6.1",9200,"http"
//)));
//创建批量请求
BulkRequest bulkRequest = new BulkRequest();
//bulkRequest.add(new IndexRequest("sse_test").id("7").source(XContentType.JSON,"qq","哆啦A梦","weixin","123456"));
Map<String,Object> map = new HashMap<>();
map.put("qq","123456789");
map.put("weixin","123456789");
map.put("phone","123456789");
Map<String,Object> map1 = new HashMap<>();
map1.put("qq","1234");
map1.put("weixin","123456789");
map1.put("phone","1234");
bulkRequest.add(new IndexRequest("sse_test").id("9").source(map));
bulkRequest.add(new UpdateRequest("sse_test","9").doc(map1).upsert());
client.bulk(bulkRequest, RequestOptions.DEFAULT);
System.out.println("结束");
}
}
3.使用kibana连接es查看时,输入GET /sse_test/_doc/9即可查看更新后的数据
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。