Spring data elasticsearch使用方法详解
这篇文章主要介绍了Springdataelasticsearch使用方法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
一、准备
1.添加依赖
org.springframework.boot spring-boot-starter-data-elasticsearch
2.application.yml
spring: application: name:search-service data: elasticsearch: cluster-name:elasticsearch cluster-nodes:192.168.25.129:9300
3.实体类
@Data
@Document(indexName="goods",type="_doc",shards=1,replicas=0)
publicclassGoods{
@IdprivateLongid;
@Field(type=FieldType.text,analyzer="ik_max_word")
privateStringall;
@Field(type=FieldType.keyword,index=false)
privateStringsubTitle;privateLongbrandId;privateLongcid1;privateLongcid2;privateLongcid3;privateDatecreateTime;privateListprice;
@Field(type=FieldType.keyword,index=false)
privateStringskus;privateMapspecs;
}
@Document作用在类,标记实体类为文档对象,一般有两个属性
- indexName:对应索引库名称
- type:对应在索引库中的类型
- shards:分片数量,默认5
- replicas:副本数量,默认1
- @Id作用在成员变量,标记一个字段作为id主键
- @Field作用在成员变量,标记为文档的字段,并指定字段映射属性:
- type:字段类型,取值是枚举:FieldType
- index:是否索引,布尔类型,默认是true
- store:是否存储,布尔类型,默认是false
- analyzer:分词器名称
二.、索引操作
首先注入ElasticsearchTemplate
@Resource privateElasticsearchTemplateelasticsearchTemplate;
●创建索引
elasticsearchTemplate.createIndex(Goods.class);
●配置映射
elasticsearchTemplate.putMapping(Goods.class);
●删除索引
//根据类
elasticsearchTemplate.deleteIndex(Goods.class);
//根据索引名
elasticsearchTemplate.deleteIndex("goods");
三、文档操作
1.定义接口。也是SpringData风格
publicinterfaceItemRepositoryextendsElasticsearchRepository- { }
2.注入
@Autowired privateItemRepositoryitemRepository;
●新增文档
Itemitem=newItem(1L,"小米手机7","手机", "小米",3499.00,"http://image.leyou.com/13123.jpg"); itemRepository.save(item);
●批量新增
List- list=newArrayList<>(); list.add(newItem(2L,"坚果手机R1","手机","锤子",3699.00,"http://image.leyou.com/123.jpg")); list.add(newItem(3L,"华为META10","手机","华为",4499.00,"http://image.leyou.com/3.jpg")); //接收对象集合,实现批量新增 itemRepository.saveAll(list);
四、基本搜索
●基本查询。
例:
//查询全部,并安装价格降序排序 Iterable- items=this.itemRepository.findAll(Sort.by(Sort.Direction.DESC,"price")); items.forEach(item->System.out.println(item));
●自定义查询
| Keyword | Sample | ElasticsearchQueryString |
|---|---|---|
| And | findByNameAndPrice | {"bool":{"must":[{"field":{"name":"?"}},{"field":{"price":"?"}}]}} |
| Or | findByNameOrPrice | {"bool":{"should":[{"field":{"name":"?"}},{"field":{"price":"?"}}]}} |
| Is | findByName | {"bool":{"must":{"field":{"name":"?"}}}} |
| Not | findByNameNot | {"bool":{"must_not":{"field":{"name":"?"}}}} |
| Between | findByPriceBetween | {"bool":{"must":{"range":{"price":{"from":?,"to":?,"include_lower":true,"include_upper":true}}}}} |
| LessThanEqual | findByPriceLessThan | {"bool":{"must":{"range":{"price":{"from":null,"to":?,"include_lower":true,"include_upper":true}}}}} |
| GreaterThanEqual | findByPriceGreaterThan | {"bool":{"must":{"range":{"price":{"from":?,"to":null,"include_lower":true,"include_upper":true}}}}} |
| Before | findByPriceBefore | {"bool":{"must":{"range":{"price":{"from":null,"to":?,"include_lower":true,"include_upper":true}}}}} |
| After | findByPriceAfter | {"bool":{"must":{"range":{"price":{"from":?,"to":null,"include_lower":true,"include_upper":true}}}}} |
| Like | findByNameLike | {"bool":{"must":{"field":{"name":{"query":"?*","analyze_wildcard":true}}}}} |
| StartingWith | findByNameStartingWith | {"bool":{"must":{"field":{"name":{"query":"?*","analyze_wildcard":true}}}}} |
| EndingWith | findByNameEndingWith | {"bool":{"must":{"field":{"name":{"query":"*?","analyze_wildcard":true}}}}} |
| Contains/Containing | findByNameContaining | {"bool":{"must":{"field":{"name":{"query":"**?**","analyze_wildcard":true}}}}} |
| In | findByNameIn(Collection |
{"bool":{"must":{"bool":{"should":[{"field":{"name":"?"}},{"field":{"name":"?"}}]}}}} |
| NotIn | findByNameNotIn(Collection |
{"bool":{"must_not":{"bool":{"should":{"field":{"name":"?"}}}}}} |
| Near | findByStoreNear | NotSupportedYet! |
| True | findByAvailableTrue | {"bool":{"must":{"field":{"available":true}}}} |
| False | findByAvailableFalse | {"bool":{"must":{"field":{"available":false}}}} |
| OrderBy | findByAvailableTrueOrderByNameDesc | {"sort":[{"name":{"order":"desc"}}],"bool":{"must":{"field":{"available":true}}}} |
例:
publicinterfaceItemRepositoryextendsElasticsearchRepository- { /** *根据价格区间查询 *@paramprice1 *@paramprice2 *@return */ List
- findByPriceBetween(doubleprice1,doubleprice2); }
五、高级查询
●词条查询
MatchQueryBuilderqueryBuilder=QueryBuilders.matchQuery("all","小米");
//执行查询
Iterablegoods=this.goodsRepository.search(queryBuilder);
●自定义查询
//构建查询条件
NativeSearchQueryBuilderqueryBuilder=newNativeSearchQueryBuilder();
//添加基本的分词查询
queryBuilder.withQuery(QueryBuilders.matchQuery("all","小米"));
//执行搜索,获取结果
Pagegoods=this.goodsRepository.search(queryBuilder.build());
//打印总条数
System.out.println(goods.getTotalElements());
//打印总页数
System.out.println(goods.getTotalPages());
●分页查询
//构建查询条件
NativeSearchQueryBuilderqueryBuilder=newNativeSearchQueryBuilder();
//添加基本的分词查询
queryBuilder.withQuery(QueryBuilders.termQuery("all","手机"));
//初始化分页参数
intpage=0;
intsize=3;
//设置分页参数
queryBuilder.withPageable(PageRequest.of(page,size));
//执行搜索,获取结果
Pagegoods=this.goodsRepository.search(queryBuilder.build());
//打印总条数
System.out.println(goods.getTotalElements());
//打印总页数
System.out.println(goods.getTotalPages());
//每页大小
System.out.println(goods.getSize());
//当前页
System.out.println(goods.getNumber());
●排序
//构建查询条件
NativeSearchQueryBuilderqueryBuilder=newNativeSearchQueryBuilder();
//添加基本的分词查询
queryBuilder.withQuery(QueryBuilders.termQuery("all","手机"));
//排序
queryBuilder.withSort(SortBuilders.fieldSort("price").order(SortOrder.DESC));
//执行搜索,获取结果
Pagegoods=this.goodsRepository.search(queryBuilder.build());
//打印总条数
System.out.println(goods.getTotalElements());
●聚合为桶
NativeSearchQueryBuilderqueryBuilder=newNativeSearchQueryBuilder();
//不查询任何结果
queryBuilder.withSourceFilter(newFetchSourceFilter(newString[]{""},null));
//1、添加一个新的聚合,聚合类型为terms,聚合名称为brands,聚合字段为brand
queryBuilder.addAggregation(AggregationBuilders.terms("brands").field("brandId"));
//2、查询,需要把结果强转为AggregatedPage类型
AggregatedPageaggPage=(AggregatedPage)this.goodsRepository.search(queryBuilder.build());
//3、解析
//3.1、从结果中取出名为brands的那个聚合,
//因为是利用String类型字段来进行的term聚合,所以结果要强转为StringTerm类型
LongTermsagg=(LongTerms)aggPage.getAggregation("brands");
//3.2、获取桶
Listbuckets=agg.getBuckets();
//3.3、遍历
for(LongTerms.Bucketbucket:buckets){
//3.4、获取桶中的key,即品牌名称
System.out.println(bucket.getKeyAsString());
//3.5、获取桶中的文档数量
System.out.println(bucket.getDocCount());
}
●嵌套聚合,求平均值
NativeSearchQueryBuilderqueryBuilder=newNativeSearchQueryBuilder();
//不查询任何结果
queryBuilder.withSourceFilter(newFetchSourceFilter(newString[]{""},null));
//1、添加一个新的聚合,聚合类型为terms,聚合名称为brands,聚合字段为brand
queryBuilder.addAggregation(AggregationBuilders.terms("brands").field("brandId")
.subAggregation(AggregationBuilders.avg("priceAvg").field("price")));//在品牌聚合桶内进行嵌套聚合,求平均值
//2、查询,需要把结果强转为AggregatedPage类型
AggregatedPageaggPage=(AggregatedPage)this.goodsRepository.search(queryBuilder.build());
//3、解析
//3.1、从结果中取出名为brands的那个聚合,
//因为是利用String类型字段来进行的term聚合,所以结果要强转为StringTerm类型
LongTermsagg=(LongTerms)aggPage.getAggregation("brands");
//3.2、获取桶
Listbuckets=agg.getBuckets();
//3.3、遍历
for(LongTerms.Bucketbucket:buckets){
//3.4、获取桶中的key,即品牌名称3.5、获取桶中的文档数量
System.out.println(bucket.getKeyAsString()+",共"+bucket.getDocCount()+"台");
//3.6.获取子聚合结果:
InternalAvgavg=(InternalAvg)bucket.getAggregations().asMap().get("priceAvg");
System.out.println("平均售价:"+avg.getValue());
}
附:配置搜索结果不显示为null字段:
spring: jackson: default-property-inclusion:non_null#配置json处理时忽略空值
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。