標籤:span creat tee 擷取 instance index clust col string
版本背景:
<dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>transport</artifactId> <version>5.4.1</version></dependency>
首先擷取es的串連:
/ /設定叢集名稱 private static final Settings settings = Settings.builder().put("cluster.name", "my-application").build();// 叢集名 //建立client private static final client = new PreBuiltTransportClient(settings) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
建立索引並建立映射
public String create(Map<String, Object> map) { IndexResponse response = client .prepareIndex("index", "type", "主鍵id") .setSource( XContentFactory.jsonBuilder().startObject() .field("業務欄位1", "業務欄位1的值") .field("業務欄位2", "業務欄位2的值") .endObject()).execute() .actionGet(); } return "success"; }
刪除,根據主鍵id
public String deleteESInfo(Map<String, Object> map) { DeleteResponse deleteresponse =client.prepareDelete( "index", "type", "主鍵id") .execute() .actionGet(); result=deleteresponse.getResult().toString(); return result; }
但是這個只是根據主鍵刪除,如果根據條件查詢去刪除那?之前在 2.X版本裡 這個Delete By Query功能被去掉了 因為官方認為會引發一些錯誤 如需使用 需要自己安裝delete-by-query外掛程式。5.0版本以上,又選擇迴歸。來條件刪除
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery(); queryBuilder.must(QueryBuilders.termQuery("業務欄位1", "業務欄位1的值")); BulkByScrollResponse response = DeleteByQueryAction.INSTANCE.newRequestBuilder(client) .filter(queryBuilder) .source("index") .get(); long deleted = response.getDeleted();
然後就是根據主鍵去更新es資訊,其中,沒有出現在field裡面去更新的,不覆蓋原有值。
UpdateResponse response = ElasticsearchConfig.client.prepareUpdate("index", "type", "主鍵id") .setDoc(XContentFactory.jsonBuilder() .startObject() .field("業務欄位1", "2") .field("業務欄位2", "1") .endObject()).execute() .actionGet();
Elasticsearch Java Api-5.x刪除和更新索引資料