您好,登錄后才能下訂單哦!
小編給大家分享一下ELASTICSEARCH如何實現JAVA的增刪改查,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
<!--elasticsear使用的jar --> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>transport</artifactId> <version>${elasticsearch.client.version}</version> </dependency> <!--elasticsear使用的jar -->
我的版本是5.4.0
我是使用spring的bean注入的
@SuppressWarnings("resource") @Bean(name="transportClient") @Lazy public TransportClient getTransportClient(){ TransportClient client =null; try{ Settings settings= Settings.builder().put("cluster.name", "elasticsearch").build(); client=new PreBuiltTransportClient(settings).addTransportAddress( new InetSocketTransportAddress(InetAddress.getByName("192.168.0.11"),9300)); log.info("創建es客戶端對象成功"); }catch(Exception e){ log.error("創建es客戶端對象失敗"); log.error("失敗原因:"+e.getMessage()); System.exit(-1); } return client; }
創建對象那個成功后,就可以用來操作es庫了,他的作用跟spring-jdbctemplate,spring-jdbctemplate一樣,提供了對數據庫增刪改查的功能,
spring也提供了對es操作的對象叫Spring Data Elasticsearch
參考文檔:
http://www.ibm.com/developerworks/cn/opensource/os-cn-spring-jpa
我用的就是es自己提供的對象 TransportClient
es的添加數據提供了多種方法,跟hql語言有點相似,都是面向對象的。
es支持批量操作的方法,為了提供效率都是用批量的對象
BulkRequestBuilder builder=transportClient.prepareBulk();
BulkRequestBuilder 對象有一個地方需要注意,因為是批量操作,es忽略了數據的不正確性,就算你的數據不對,builder也不會報錯,所以在調試階段需要先確保數據的準確性再用該對象進行操作。
插入數據,其實只需要把你的對象轉成json,然后批量插入即可
@Override public void batchAddMyZu(List<Family> list) { BulkRequestBuilder builder=transportClient.prepareBulk(); for(Family family:list){ String objstr= JSON.toJSONString(family); builder.add(client.prepareIndex("family","myfamily",family.getPrimaryKey()).setSource(objstr, XContentType.JSON)); } builder.execute().actionGet(); System.out.println("此次插入數據的個數是 "+list.size()); }
setSource方法里面可以指定各種插入類型,我一般都是用json格式。
es可以通過指定index,type,id刪除數據,也支持搜索刪除deleteByQuery
通過指定id刪除方法
@Override public void batchUndercarriageFamilies(List<String> publishIds) { BulkRequestBuilder builder=transportClient.prepareBulk(); for(String publishId:publishIds){ builder.add(transportClient.prepareDelete(FAMILY, FAMILY_MARKETFAMILY, publishId).request()); } builder.get(); }
通過deleteByQuery刪除
@Override public void delMyZu(String guid, String userId) { DeleteByQueryAction.INSTANCE.newRequestBuilder(transportClient) .source(FAMILY) .filter(QueryBuilders.boolQuery().must(QueryBuilders.termQuery("zuGUID", guid)).must(QueryBuilders.termQuery("userId", userId)).must(QueryBuilders.typeQuery(FAMILY_MYFAMILY))) .get(); }
QueryBuilder對象可以做任何查詢
我現在修改是根據指定索引后然后修改指定字段醬樣的
@Override public void updateMyZu_Related4MyZuValue(List<Related4MyZuValue> list) { BulkRequestBuilder builder=transportClient.prepareBulk(); for(Related4MyZuValue value:list){ try { XContentBuilder source=XContentFactory.jsonBuilder().startObject() .field("related4ZuValue",value.getRelated4ZuValue()) .field("zuSalePrice",value.getZuSalePrice()) .endObject(); builder.add(transportClient.prepareUpdate(FAMILY, FAMILY_MYFAMILY, value.getPrimaryKey()).setDoc(source)); } catch (IOException e) { continue; } } builder.get(); }
我這種操作是執行id后修改該數據的related4ZuValue的值和zuSalePrice的值
es最主要功能就是查詢
QueryBuilder就是設置查詢條件的對象,你可以通過他設置各種條件
隨便貼幾個,自己感受吧。。。。
BoolQueryBuilder boolQueryBuilder=QueryBuilders.boolQuery(); if(keyword!=null&&!keyword.equals("")){ QueryBuilder nameBuilder=QueryBuilders.matchQuery("zuName", keyword).analyzer("ik_max_word").boost(10); QueryBuilder labelBuilder=QueryBuilders.matchQuery("zuLabelName", keyword).analyzer("ik_max_word").boost(10); QueryBuilder categoryBuilder=QueryBuilders.matchQuery("categoryName", keyword).analyzer("ik_max_word").boost(10); boolQueryBuilder.should(nameBuilder).should(labelBuilder).should(categoryBuilder); }else{ boolQueryBuilder.must(QueryBuilders.matchAllQuery()); } SearchResponse response=transportClient.prepareSearch(FAMILY).setTypes(FAMILY_MARKETFAMILY) .setQuery(boolQueryBuilder) .setFrom((page-1)*pageSize).setSize(pageSize) .setExplain(true) .get(); SearchHits hits=response.getHits();
BoolQueryBuilder builders=new BoolQueryBuilder(); //加上條件 builders.must(QueryBuilders.termQuery("userId", userId)); if(relatedValue==RelatedValue.MyBuyerZu.value()){ builders.must(QueryBuilders.nestedQuery("related4ZuValue", QueryBuilders.boolQuery() .must(QueryBuilders.termQuery("related4ZuValue.nameValue", UserReltatedValueUtil.getUserRelatedValue(relatedValue))) //.must(QueryBuilders.rangeQuery("endTime").lte(LongformStringDate(System.currentTimeMillis()))) ,ScoreMode.None)); }else{ builders.must(QueryBuilders.nestedQuery("related4ZuValue", QueryBuilders.termQuery("related4ZuValue.nameValue", UserReltatedValueUtil.getUserRelatedValue(relatedValue)), ScoreMode.None)); } SearchResponse response=transportClient.prepareSearch(FAMILY).setTypes(FAMILY_MYFAMILY) .setQuery(builders).setFrom((page-1)*pageSize) .setSize(pageSize) .get(); SearchHits hits=response.getHits();
@Override public MarketFamily getMarketFamily(String guid) { MarketFamily marketFamily=new MarketFamily(); SearchResponse response=transportClient.prepareSearch(FAMILY) .setTypes(FAMILY_MYFAMILY).setQuery(QueryBuilders.termQuery("zuGUID", guid)) .setSize(1) .get(); SearchHits hits=response.getHits(); for(SearchHit hit:hits.getHits()){ marketFamily=JSON.parseObject(hit.getSourceAsString(),MarketFamily.class); } return marketFamily; }
@Override public long countMyAllZu(String userId, int relatedValue) { BoolQueryBuilder builders=new BoolQueryBuilder(); builders.must(QueryBuilders.termQuery("userId", userId)); if(relatedValue==RelatedValue.MyBuyerZu.value()){ builders.must(QueryBuilders.nestedQuery("related4ZuValue", QueryBuilders.boolQuery() .must(QueryBuilders.termQuery("related4ZuValue.nameValue", UserReltatedValueUtil.getUserRelatedValue(relatedValue))) .must(QueryBuilders.rangeQuery("endTime").lte(LongformStringDate(System.currentTimeMillis()))) ,ScoreMode.None)); }else{ builders.must(QueryBuilders.nestedQuery("related4ZuValue", QueryBuilders.termQuery("related4ZuValue.nameValue", UserReltatedValueUtil.getUserRelatedValue(relatedValue)), ScoreMode.None)); } SearchResponse response=transportClient.prepareSearch(FAMILY).setTypes(FAMILY_MYFAMILY) .setQuery(builders) .setSize(1) .get(); SearchHits hits=response.getHits(); return hits.getTotalHits(); }
@Override public long getPlatformZuOrdersTotalAmount(String keyword,String startTime,String endTime) { BoolQueryBuilder boolQueryBuilder=QueryBuilders.boolQuery(); if(keyword==null||keyword.equals("")){ QueryBuilder queryBuilder=QueryBuilders.matchAllQuery(); boolQueryBuilder.must(queryBuilder); }else{ QueryBuilder zuNameBuilder=QueryBuilders.matchQuery("zuName", keyword); QueryBuilder buyerNameBuilder=QueryBuilders.matchQuery("buyerName", keyword); QueryBuilder sellerNameBuilder=QueryBuilders.matchQuery("sellerName", keyword); boolQueryBuilder.should(zuNameBuilder).should(buyerNameBuilder).should(sellerNameBuilder); } if(!startTime.equals("")){ QueryBuilder addTimeBuilder=QueryBuilders.rangeQuery("addTime").from(startTime).to(endTime); boolQueryBuilder.must(addTimeBuilder); } SearchResponse response=transportClient.prepareSearch(FAMILY).setTypes(FAMILY_FAMILYORDER) .setQuery(boolQueryBuilder) .addAggregation(AggregationBuilders.sum("price").field("price")) .get(); Sum sum=response.getAggregations().get("price"); return (long) sum.getValue(); }
以上是“ELASTICSEARCH如何實現JAVA的增刪改查”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。