共计 7241 个字符,预计需要花费 19 分钟才能阅读完成。
丸趣 TV 小编给大家分享一下 ELASTICSEARCH 如何实现 JAVA 的增删改查,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
操作 ES 的对象:TransportClient
!--elasticsear 使用的 jar --
dependency
groupId org.elasticsearch.client /groupId
artifactId transport /artifactId
version ${elasticsearch.client.version} /version
/dependency
!--elasticsear 使用的 jar --
我的版本是 5.4.0
创建 TransportClient 对象
我是使用 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;
}
取查询结果总和 count
@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();}
聚合求和 sum
@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 的增删改查”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注丸趣 TV 行业资讯频道!