您好,登錄后才能下訂單哦!
本篇文章給大家分享的是有關(guān)Spring data中elasticsearch如何使用,小編覺得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
1.添加依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency>
2.application.yml
spring: application: name: search-service data: elasticsearch: cluster-name: elasticsearch cluster-nodes: 192.168.25.129:9300
3.實(shí)體類
@Data @Document(indexName = "goods", type = "_doc", shards = 1, replicas = 0) public class Goods { @Idprivate Long id; @Field(type = FieldType.text, analyzer = "ik_max_word") private String all; @Field(type = FieldType.keyword, index = false) private String subTitle;private Long brandId;private Long cid1;private Long cid2;private Long cid3;private Date createTime;private List<Long> price; @Field(type = FieldType.keyword, index = false) private String skus;private Map<String, Object> specs; }
@Document 作用在類,標(biāo)記實(shí)體類為文檔對象,一般有兩個(gè)屬性
indexName:對應(yīng)索引庫名稱
type:對應(yīng)在索引庫中的類型
shards:分片數(shù)量,默認(rèn)5
replicas:副本數(shù)量,默認(rèn)1
@Id 作用在成員變量,標(biāo)記一個(gè)字段作為id主鍵
@Field 作用在成員變量,標(biāo)記為文檔的字段,并指定字段映射屬性:
type:字段類型,取值是枚舉:FieldType
index:是否索引,布爾類型,默認(rèn)是true
store:是否存儲(chǔ),布爾類型,默認(rèn)是false
analyzer:分詞器名稱
二.、索引操作
首先注入ElasticsearchTemplate
@Resource private ElasticsearchTemplate elasticsearchTemplate;
● 創(chuàng)建索引
elasticsearchTemplate.createIndex(Goods.class);
● 配置映射
elasticsearchTemplate.putMapping(Goods.class);
● 刪除索引
//根據(jù)類 elasticsearchTemplate.deleteIndex(Goods.class); //根據(jù)索引名 elasticsearchTemplate.deleteIndex("goods");
三、文檔操作
1.定義接口。也是SpringData風(fēng)格
public interface ItemRepository extends ElasticsearchRepository<Item,Long> { }
2.注入
@Autowired private ItemRepository itemRepository;
● 新增文檔
Item item = new Item(1L, "小米手機(jī)7", " 手機(jī)", "小米", 3499.00, "http://image.leyou.com/13123.jpg"); itemRepository.save(item);
● 批量新增
List<Item> list = new ArrayList<>(); list.add(new Item(2L, "堅(jiān)果手機(jī)R1", " 手機(jī)", "錘子", 3699.00, "http://image.leyou.com/123.jpg")); list.add(new Item(3L, "華為META10", " 手機(jī)", "華為", 4499.00, "http://image.leyou.com/3.jpg")); // 接收對象集合,實(shí)現(xiàn)批量新增 itemRepository.saveAll(list);
四、 基本搜索
● 基本查詢。
例:
// 查詢?nèi)?,并安裝價(jià)格降序排序 Iterable<Item> items = this.itemRepository.findAll(Sort.by(Sort.Direction.DESC, "price")); items.forEach(item-> System.out.println(item));
● 自定義查詢
Keyword | Sample | Elasticsearch Query String |
---|---|---|
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<String>names) | {"bool" : {"must" : {"bool" : {"should" : [ {"field" : {"name" : "?"}}, {"field" : {"name" : "?"}} ]}}}} |
NotIn | findByNameNotIn(Collection<String>names) | {"bool" : {"must_not" : {"bool" : {"should" : {"field" : {"name" : "?"}}}}}} |
Near | findByStoreNear | Not Supported Yet ! |
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}}}} |
例:
public interface ItemRepository extends ElasticsearchRepository<Item,Long> { /** * 根據(jù)價(jià)格區(qū)間查詢 * @param price1 * @param price2 * @return */ List<Item> findByPriceBetween(double price1, double price2); }
五、高級查詢
● 詞條查詢
MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery("all", "小米"); // 執(zhí)行查詢 Iterable<Goods> goods = this.goodsRepository.search(queryBuilder);
● 自定義查詢
// 構(gòu)建查詢條件 NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder(); // 添加基本的分詞查詢 queryBuilder.withQuery(QueryBuilders.matchQuery("all", "小米")); // 執(zhí)行搜索,獲取結(jié)果 Page<Goods> goods = this.goodsRepository.search(queryBuilder.build()); // 打印總條數(shù) System.out.println(goods.getTotalElements()); // 打印總頁數(shù) System.out.println(goods.getTotalPages());
● 分頁查詢
// 構(gòu)建查詢條件 NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder(); // 添加基本的分詞查詢 queryBuilder.withQuery(QueryBuilders.termQuery("all", "手機(jī)")); // 初始化分頁參數(shù) int page = 0; int size = 3; // 設(shè)置分頁參數(shù) queryBuilder.withPageable(PageRequest.of(page, size)); // 執(zhí)行搜索,獲取結(jié)果 Page<Goods> goods = this.goodsRepository.search(queryBuilder.build()); // 打印總條數(shù) System.out.println(goods.getTotalElements()); // 打印總頁數(shù) System.out.println(goods.getTotalPages()); // 每頁大小 System.out.println(goods.getSize()); // 當(dāng)前頁 System.out.println(goods.getNumber());
● 排序
// 構(gòu)建查詢條件 NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder(); // 添加基本的分詞查詢 queryBuilder.withQuery(QueryBuilders.termQuery("all", "手機(jī)")); // 排序 queryBuilder.withSort(SortBuilders.fieldSort("price").order(SortOrder.DESC)); // 執(zhí)行搜索,獲取結(jié)果 Page<Goods> goods = this.goodsRepository.search(queryBuilder.build()); // 打印總條數(shù) System.out.println(goods.getTotalElements());
● 聚合為桶
NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder(); // 不查詢?nèi)魏谓Y(jié)果 queryBuilder.withSourceFilter(new FetchSourceFilter(new String[]{""}, null)); // 1、添加一個(gè)新的聚合,聚合類型為terms,聚合名稱為brands,聚合字段為brand queryBuilder.addAggregation(AggregationBuilders.terms("brands").field("brandId")); // 2、查詢,需要把結(jié)果強(qiáng)轉(zhuǎn)為AggregatedPage類型 AggregatedPage<Goods> aggPage = (AggregatedPage<Goods>) this.goodsRepository.search(queryBuilder.build()); // 3、解析 // 3.1、從結(jié)果中取出名為brands的那個(gè)聚合, // 因?yàn)槭抢肧tring類型字段來進(jìn)行的term聚合,所以結(jié)果要強(qiáng)轉(zhuǎn)為StringTerm類型 LongTerms agg = (LongTerms) aggPage.getAggregation("brands"); // 3.2、獲取桶 List<LongTerms.Bucket> buckets = agg.getBuckets(); // 3.3、遍歷 for (LongTerms.Bucket bucket : buckets) { // 3.4、獲取桶中的key,即品牌名稱 System.out.println(bucket.getKeyAsString()); // 3.5、獲取桶中的文檔數(shù)量 System.out.println(bucket.getDocCount()); }
● 嵌套聚合,求平均值
NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder(); // 不查詢?nèi)魏谓Y(jié)果 queryBuilder.withSourceFilter(new FetchSourceFilter(new String[]{""}, null)); // 1、添加一個(gè)新的聚合,聚合類型為terms,聚合名稱為brands,聚合字段為brand queryBuilder.addAggregation(AggregationBuilders.terms("brands").field("brandId") .subAggregation(AggregationBuilders.avg("priceAvg").field("price"))); // 在品牌聚合桶內(nèi)進(jìn)行嵌套聚合,求平均值 // 2、查詢,需要把結(jié)果強(qiáng)轉(zhuǎn)為AggregatedPage類型 AggregatedPage<Goods> aggPage = (AggregatedPage<Goods>) this.goodsRepository.search(queryBuilder.build()); // 3、解析 // 3.1、從結(jié)果中取出名為brands的那個(gè)聚合, // 因?yàn)槭抢肧tring類型字段來進(jìn)行的term聚合,所以結(jié)果要強(qiáng)轉(zhuǎn)為StringTerm類型 LongTerms agg = (LongTerms) aggPage.getAggregation("brands"); // 3.2、獲取桶 List<LongTerms.Bucket> buckets = agg.getBuckets(); // 3.3、遍歷 for (LongTerms.Bucket bucket : buckets) { // 3.4、獲取桶中的key,即品牌名稱 3.5、獲取桶中的文檔數(shù)量 System.out.println(bucket.getKeyAsString() + ",共" + bucket.getDocCount() + "臺(tái)"); // 3.6.獲取子聚合結(jié)果: InternalAvg avg = (InternalAvg) bucket.getAggregations().asMap().get("priceAvg"); System.out.println("平均售價(jià):" + avg.getValue()); }
附:配置搜索結(jié)果不顯示為null字段:
spring: jackson: default-property-inclusion: non_null # 配置json處理時(shí)忽略空值
以上就是Spring data中elasticsearch如何使用,小編相信有部分知識(shí)點(diǎn)可能是我們?nèi)粘9ぷ鲿?huì)見到或用到的。希望你能通過這篇文章學(xué)到更多知識(shí)。更多詳情敬請關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。