您好,登錄后才能下訂單哦!
小編給大家分享一下ELASTICSEARCH如何實現(xiàn)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("創(chuàng)建es客戶端對象成功"); }catch(Exception e){ log.error("創(chuàng)建es客戶端對象失敗"); log.error("失敗原因:"+e.getMessage()); System.exit(-1); } return client; }
創(chuàng)建對象那個成功后,就可以用來操作es庫了,他的作用跟spring-jdbctemplate,spring-jdbctemplate一樣,提供了對數(shù)據(jù)庫增刪改查的功能,
spring也提供了對es操作的對象叫Spring Data Elasticsearch
參考文檔:
http://www.ibm.com/developerworks/cn/opensource/os-cn-spring-jpa
我用的就是es自己提供的對象 TransportClient
es的添加數(shù)據(jù)提供了多種方法,跟hql語言有點相似,都是面向?qū)ο蟮摹?/p>
es支持批量操作的方法,為了提供效率都是用批量的對象
BulkRequestBuilder builder=transportClient.prepareBulk();
BulkRequestBuilder 對象有一個地方需要注意,因為是批量操作,es忽略了數(shù)據(jù)的不正確性,就算你的數(shù)據(jù)不對,builder也不會報錯,所以在調(diào)試階段需要先確保數(shù)據(jù)的準(zhǔn)確性再用該對象進行操作。
插入數(shù)據(jù),其實只需要把你的對象轉(zhuǎn)成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("此次插入數(shù)據(jù)的個數(shù)是 "+list.size()); }
setSource方法里面可以指定各種插入類型,我一般都是用json格式。
es可以通過指定index,type,id刪除數(shù)據(jù),也支持搜索刪除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對象可以做任何查詢
我現(xiàn)在修改是根據(jù)指定索引后然后修改指定字段醬樣的
@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(); }
我這種操作是執(zhí)行id后修改該數(shù)據(jù)的related4ZuValue的值和zuSalePrice的值
es最主要功能就是查詢
QueryBuilder就是設(shè)置查詢條件的對象,你可以通過他設(shè)置各種條件
隨便貼幾個,自己感受吧。。。。
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如何實現(xiàn)JAVA的增刪改查”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。