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

📅 2026/8/3 16:52:07 👁️ 阅读次数 📝 编程学习
SpringBoot 整合 Elasticsearch 实战——搜索、高亮、聚合

一、依赖与配置

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-elasticsearch</artifactId></dependency>
spring:elasticsearch:uris:http://localhost:9200

二、实体与 Repository

@Document(indexName="products")publicclassProduct{@IdprivateLongid;@Field(type=FieldType.Text,analyzer="ik_max_word")privateStringtitle;@Field(type=FieldType.Keyword)privateStringbrand;@Field(type=FieldType.Double)privateDoubleprice;}
publicinterfaceProductRepositoryextendsElasticsearchRepository<Product,Long>{}

三、搜索(带高亮)

@ServicepublicclassProductSearchService{@AutowiredprivateElasticsearchRestTemplatetemplate;publicList<Product>search(Stringkeyword){NativeQueryquery=NativeQuery.builder().withQuery(q->q.multiMatch(m->m.fields("title","brand").query(keyword))).withHighlight(h->h.fields("title",f->f.preTags("<em>").postTags("</em>"))).build();SearchHits<Product>hits=template.search(query,Product.class);returnhits.stream().map(SearchHit::getContent).toList();}}

四、聚合查询

publicMap<String,Long>aggregateByBrand(){NativeQueryquery=NativeQuery.builder().withAggregation("brands",a->a.terms(t->t.field("brand.keyword"))).build();SearchHits<Product>hits=template.search(query,Product.class);returnhits.getAggregations().get("brands").terms().buckets().stream().collect(Collectors.toMap(b->b.key().stringValue(),b->b.docCount()));}

💡 觉得有用的话,点赞 + 关注【张老师技术栈】吧!