小编给大家分享一下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
参考文档:
我用的就是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的增删改查”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注天达云行业资讯频道!