SpringBoot 整合 Elasticsearch 实战——搜索、高亮、聚合

📅 2026/8/3 16:40:24
SpringBoot 整合 Elasticsearch 实战——搜索、高亮、聚合
一、依赖与配置dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-data-elasticsearch/artifactId/dependencyspring:elasticsearch:uris:http://localhost:9200二、实体与 RepositoryDocument(indexNameproducts)publicclassProduct{IdprivateLongid;Field(typeFieldType.Text,analyzerik_max_word)privateStringtitle;Field(typeFieldType.Keyword)privateStringbrand;Field(typeFieldType.Double)privateDoubleprice;}publicinterfaceProductRepositoryextendsElasticsearchRepositoryProduct,Long{}三、搜索带高亮ServicepublicclassProductSearchService{AutowiredprivateElasticsearchRestTemplatetemplate;publicListProductsearch(Stringkeyword){NativeQueryqueryNativeQuery.builder().withQuery(q-q.multiMatch(m-m.fields(title,brand).query(keyword))).withHighlight(h-h.fields(title,f-f.preTags(em).postTags(/em))).build();SearchHitsProducthitstemplate.search(query,Product.class);returnhits.stream().map(SearchHit::getContent).toList();}}四、聚合查询publicMapString,LongaggregateByBrand(){NativeQueryqueryNativeQuery.builder().withAggregation(brands,a-a.terms(t-t.field(brand.keyword))).build();SearchHitsProducthitstemplate.search(query,Product.class);returnhits.getAggregations().get(brands).terms().buckets().stream().collect(Collectors.toMap(b-b.key().stringValue(),b-b.docCount()));} 觉得有用的话点赞 关注【张老师技术栈】吧