In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces how to use Springdataelasticsearch, the introduction in the article is very detailed, has a certain reference value, interested friends must read!
I. preparation
1. Add dependency
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. Entity class
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 price; @ Field (type = FieldType.keyword, index = false) private String skus;private Map specs;}
@ Document acts on the class, marking the entity class as a document object, and generally has two attributes
IndexName: corresponding index library name type: corresponding to the type in the index library shards: number of fragments, default is 5 replicas: number of copies, default 1 @ Id acts on member variables, marks a field as id primary key @ Field acts on member variables, marks fields marked as document, and specifies field mapping attribute: type: field type, values are enumerated: FieldType index: whether to index, Boolean type, default is true store: whether to store Boolean type, default is false analyzer: splitter name
2. Index operation
First inject ElasticsearchTemplate
@ Resourceprivate ElasticsearchTemplate elasticsearchTemplate
● creates an index
ElasticsearchTemplate.createIndex (Goods.class)
● configuration Mapping
ElasticsearchTemplate.putMapping (Goods.class)
● delete index
/ / according to the class elasticsearchTemplate.deleteIndex (Goods.class); / / according to the index name elasticsearchTemplate.deleteIndex ("goods")
III. Document operation
1. Define the interface. It's also SpringData style.
Public interface ItemRepository extends ElasticsearchRepository {}
two。 Inject
@ Autowiredprivate ItemRepository itemRepository
New documents for ●
Item item = new Item (1L, "Xiaomi Mobile 7", "Mobile", "Xiaomi", 3499.00, "http://image.leyou.com/13123.jpg");itemRepository.save(item);"
● added in batch
List list = new ArrayList (); list.add (new Item (2L, "Nut phone R1", "Mobile", "Hammer", 3699.00, "http://image.leyou.com/123.jpg")); list.add (new Item (3L," Huawei META10 "," Mobile "," Huawei ", 4499.00," http://image.leyou.com/3.jpg")); " / / receive a collection of objects to add itemRepository.saveAll (list) in batch
IV. Basic search
● basic query.
Example:
/ / query all and sort the installation prices in descending order Iterable items = this.itemRepository.findAll (Sort.by (Sort.Direction.DESC, "price"); items.forEach (item- > System.out.println (item))
● Custom query
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": {"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": {"query": "*?" "analyze_wildcard": true} Contains/Containing findByNameContaining {"bool": {"must": {"name": {"query": "* *? *", "analyze_wildcard": true} In findByNameIn (Collectionnames) {"bool": {"must": {"bool": {"should": [{"field": {"name": "?"}} {"field": {"name": "?"} NotIn findByNameNotIn (Collectionnames) {"bool": {"must_not": {"bool": {"should": {"field": {"name": "?"} Near findByStoreNear Not Supported Yet! True findByAvailableTrue {"bool": {"field": {"available": true} False findByAvailableFalse {"bool": {"must": {"field": {"available": false} OrderBy findByAvailableTrueOrderByNameDesc {"sort": [{"name": {"order": "desc"}], "bool": {"must": {"field": {"available": true}
Example:
Public interface ItemRepository extends ElasticsearchRepository {/ * query * @ param price1 * @ param price2 * @ return * / List findByPriceBetween (double price1, double price2) according to price range;}
KeywordSampleElasticsearch Query String
5. Advanced enquiries
● entry query
MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery ("all", "Xiaomi"); / / execute query Iterable goods = this.goodsRepository.search (queryBuilder)
● Custom query
/ / build query condition NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder (); / / add basic participle query queryBuilder.withQuery (QueryBuilders.matchQuery ("all", "Xiaomi"); / / perform search to get results Page goods = this.goodsRepository.search (queryBuilder.build ()); / / print total number of pages System.out.println (goods.getTotalElements ()); / / print total number of pages (goods.getTotalPages ())
● paging query
/ / build query condition NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder (); / / add basic word segmentation query queryBuilder.withQuery (QueryBuilders.termQuery ("all", "mobile")); / / initialize paging parameter int page = 0; int size = 3; / / set paging parameter queryBuilder.withPageable (PageRequest.of (page, size)); / / perform search to get results Page goods = this.goodsRepository.search (queryBuilder.build ()) / / Total number of printed pages System.out.println (goods.getTotalElements ()); / / Total number of printed pages System.out.println (goods.getTotalPages ()); / / per page size System.out.println (goods.getSize ()); / / current page System.out.println (goods.getNumber ())
● sorting
/ / build query condition NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder (); / / add basic participle query queryBuilder.withQuery (QueryBuilders.termQuery ("all", "mobile")); / / sort queryBuilder.withSort (SortBuilders.fieldSort ("price") .order (SortOrder.DESC)); / / perform search to get results Page goods = this.goodsRepository.search (queryBuilder.build ()); / / print total number of entries System.out.println (goods.getTotalElements ())
● aggregates into buckets
NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder (); / / do not query any result queryBuilder.withSourceFilter (new FetchSourceFilter (new String [] {""}, null)); / / 1. Add a new aggregate with aggregate type terms, aggregate name brands, aggregate field brand queryBuilder.addAggregation (AggregationBuilders.terms ("brands"). Field ("brandId"); / / 2. Query, you need to change the result to AggregatedPage type AggregatedPage aggPage = (AggregatedPage) this.goodsRepository.search (queryBuilder.build ()). / / 3, parse / / 3.1and extract the aggregate named brands from the result. / / because it is a term aggregation using String type fields, the result should be strongly converted to StringTerm type LongTerms agg = (LongTerms) aggPage.getAggregation ("brands"); / / 3.2.get bucket List buckets = agg.getBuckets () Traversing for (LongTerms.Bucket bucket: buckets) {/ / 3.4, getting the key in the bucket, that is, the brand name System.out.println (bucket.getKeyAsString ()); / / 3.5, getting the number of documents in the bucket System.out.println (bucket.getDocCount ());}
● nested aggregation, calculating the average
NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder (); / / do not query any result queryBuilder.withSourceFilter (new FetchSourceFilter (new String [] {""}, null)); / / 1. Add a new aggregate with aggregate type terms, aggregate name brands, aggregate field brand queryBuilder.addAggregation (AggregationBuilders.terms ("brands"). Field ("brandId") .subaggregation (AggregationBuilders.avg ("priceAvg"). Field ("price") / / perform nested aggregation in the brand aggregation bucket to find the average / / 2. For query, you need to change the result to AggregatedPage type AggregatedPage aggPage = (AggregatedPage) this.goodsRepository.search (queryBuilder.build ()). / / 3, parse / / 3.1and extract the aggregate named brands from the result. / / because it is a term aggregation using String type fields, the result should be strongly converted to StringTerm type LongTerms agg = (LongTerms) aggPage.getAggregation ("brands"); / / 3.2.get bucket List buckets = agg.getBuckets () / / 3.3.Take for (LongTerms.Bucket bucket: buckets) {/ / 3.4.Get the key in the bucket, that is, brand name 3.5. get the number of documents in the bucket System.out.println (bucket.getKeyAsString () + ", total" + bucket.getDocCount () + Taiwan "); / / 3.6. InternalAvg avg = (InternalAvg) bucket.getAggregations (). AsMap (). Get ("priceAvg"); System.out.println ("average selling price:" + avg.getValue ());}
Attachment: configure search results not to be displayed as null fields:
Spring: jackson: default-property-inclusion: non_null # ignore null values when configuring json processing
The above is all the contents of this article "how to use Springdataelasticsearch". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.