SpringDataElasticsearch

SpringData Elasticsearch是SpringData项目的成员之一,它基于ES的官方JavaSDK封装了一套采用Repository风格并能与Spring体系紧密集成的编程模型,包括基于注解的实体映射、Repository接口自动实现以及流畅的查询API等。这篇笔记我们以SpringBoot 3.x版本为例,简单学习一下SpringData Elasticsearch的使用。

关于ES版本绑定问题说明

ES有一个比较严重的问题是客户端SDK频繁Break Changes,从ES 6.x、7.x到现在的8.x,至今已经换了三套互不兼容的SDK,而不同版本的SpringData Elasticsearch只能集成其中某一个版本的ES客户端SDK,这也意味着如果我们使用SpringData Elasticsearch,就可能必须“自愿被绑架”到某个版本的ES上。

在SpringBoot 2.x版本中,SpringData Elasticsearch封装的是ES High Level REST Client(HLRC),这意味着仅支持ES 7.x版本,而SpringBoot 3.x版本中,SpringData Elasticsearch封装的是ES Java API Client,这意味着我们必须用ES 8.x,否则可能出现兼容性问题,如果你的实际环境不符合这一绑定关系,那么无法使用SpringData Elasticsearch!

本篇笔记使用的是SpringBoot 3.5.x,对应ES版本为8.x版本。

引入SpringData Elasticsearch

添加Maven依赖

使用SpringData Elasticsearch需要在pom.xml中引入如下起步依赖。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

添加相关配置

在application.properties中,我们添加如下配置。

spring.elasticsearch.uris=http://localhost:9200
spring.elasticsearch.connection-timeout=3s
spring.elasticsearch.socket-timeout=30s
spring.elasticsearch.socket-keep-alive=true

其中,spring.elasticsearch.uris是ES服务端的地址,如果我们使用的是集群模式,这里可以使用逗号分隔配置多个地址;spring.elasticsearch.connection-timeout配置建立连接的超时时间,默认1秒,生产环境建议配置1~3秒;spring.elasticsearch.socket-timeout配置Socket数据读写超时时间,默认30秒,生产环境可根据实际业务调整;spring.elasticsearch.socket-keep-alive配置TCP层是否保活连接,默认值为false,生产环境建议配置为true以减少频繁建立连接开销。此外如果ES服务端开启了认证,还需要配置spring.elasticsearch.username和spring.elasticsearch.password。

不过只配置以上内容还不够,生产环境建议使用RestClientBuilderCustomizer根据实际情况配置连接池最大连接数、连接保活策略等。

package com.gacfox.demo.config;

import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.springframework.boot.autoconfigure.elasticsearch.RestClientBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticsearchConfig {
    @Bean
    public RestClientBuilderCustomizer customizer() {
        return builder -> {
            // 配置Apache HttpAsyncClient
            builder.setHttpClientConfigCallback((HttpAsyncClientBuilder httpClientBuilder) -> httpClientBuilder
                    // 最大总连接数
                    .setMaxConnTotal(50)
                    // 每个路由(节点)的最大连接数
                    .setMaxConnPerRoute(10)
                    // 连接保活策略
                    .setKeepAliveStrategy((response, context) -> 60000));
        };
    }
}

这里可能有人会问,为什么SpringData Elasticsearch中仅暴露了少量配置,没有暴露高频使用的高级配置字段?这绝不是这些配置字段不重要,而且SpringBoot2.x时代SpringData Elasticsearch本来是有这些字段的,在SpringBoot 3.x下反而给移除了,这其实有历史原因,是Spring被ES官方的版本混乱坑怕了,ES客户端的迭代完全不遵守行业规则,客户端激进废弃完全不管下游生态,版本绑定灾难级严重,ES官方本身又不参与SpringData Elasticsearch的维护,Spring也没必要追着跑最后“热脸贴了冷屁股”,因此Spring做了彻底解绑,SpringData Elasticsearch决定只封装那些最核心、基本永远不可能改的参数,其余配置一律解耦,若有需要得自行通过代码配置,这其实可以理解为一种“防御性编程”,规避了客户端版本一变SpringData Elasticsearch直接不可用的尴尬情况。

实体类与索引映射

SpringData Elasticsearch通过注解将Java实体类与Elasticsearch的索引和字段建立映射关系。我们先在Elasticsearch中使用RESTful API创建一个products索引,后面相关演示操作都会基于这个索引实现。

PUT /products
{
  "mappings": {
    "properties": {
      "name": {
        "type": "text",
        "analyzer": "ik_max_word",
        "search_analyzer": "ik_smart",
        "fields": {
          "keyword": {
            "type": "keyword"
          }
        }
      },
      "description": {
        "type": "text",
        "analyzer": "ik_max_word",
        "search_analyzer": "ik_smart"
      },
      "category": { "type": "keyword" },
      "brand": { "type": "keyword" },
      "price": { "type": "double" },
      "stock": { "type": "integer" },
      "tags": { "type": "keyword" },
      "is_deleted": { "type": "boolean" },
      "created_at": {
        "type": "date",
        "format": "yyyy-MM-dd HH:mm:ss"
      },
      "location": { "type": "geo_point" }
    }
  }
}

上面代码对应的实体类如下。

package com.gacfox.demo.model;

import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.*;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;

import java.time.LocalDateTime;
import java.util.List;

@Data
@Document(indexName = "products", createIndex = false)
public class Product {
    @Id
    private String id;

    @Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
    private String name;

    @Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
    private String description;

    @Field(type = FieldType.Keyword)
    private String category;

    @Field(type = FieldType.Keyword)
    private String brand;

    @Field(type = FieldType.Double)
    private Double price;

    @Field(type = FieldType.Integer)
    private Integer stock;

    @Field(type = FieldType.Keyword)
    private List<String> tags;

    @Field(name = "is_deleted", type = FieldType.Boolean)
    private Boolean isDeleted;

    @Field(name = "created_at", type = FieldType.Date, format = {}, pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime createdAt;

    @GeoPointField
    private GeoPoint location;
}

@Document标记该类对应一个Elasticsearch索引,其中indexName属性指定索引名称。此外该注解还有一个createIndex属性,默认值为true,表示应用启动时如果索引不存在会自动创建,但由于自动创建的索引使用的是注解推断的配置,对于生产环境十分不建议自动创建,因此建议将其设置为false改为手动创建索引。

@Id标记文档的主键字段,对应Elasticsearch文档的_id,字段类型一般都应声明为String。

@Field描述字段的映射属性,type指定Elasticsearch的字段类型,analyzer和searchAnalyzer分别指定写入分析器和搜索分析器,我们这里使用IK分析器,name用于指定Elasticsearch中的字段名,由于Java字段通常都是驼峰命名,而Elasticsearch字段通常都是小写下划线命名,因此当字段名出现不一致时我们就应使用这个属性手动指定字段名映射。

@GeoPointField标记地理坐标字段,它对应Elasticsearch的geo_point类型,配合SpringData Elasticsearch提供的GeoPoint类使用。

Repository接口

SpringData Elasticsearch的Repository模式设计和写法与SpringData JPA基本一致,只需定义接口并继承ElasticsearchRepository,框架会自动提供基础的CRUD实现。

package com.gacfox.demo.repository;

import com.gacfox.demo.model.Product;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

public interface ProductRepository extends ElasticsearchRepository<Product, String> {
}

代码中,ElasticsearchRepository泛型的第一个参数是实体类型,第二个参数是主键类型。继承ElasticsearchRepository后,ProductRepository就自动拥有save()、findById()、deleteById()、findAll()等一系列标准CRUD方法了。

基础数据操作

基础CRUD

下面例子代码中,我们基于之前创建的ElasticsearchRepository实现了基础的增删改查操作。

package com.gacfox.demo.service;

import com.gacfox.demo.model.Product;
import com.gacfox.demo.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * Elasticsearch产品信息增删改查
 */
@Service("productService")
public class ProductService {
    private final ProductRepository productRepository;

    @Autowired
    public ProductService(ProductRepository productRepository) {
        this.productRepository = productRepository;
    }

    /**
     * 保存或更新产品(根据ID判断)
     *
     * @param product 产品
     * @return 产品
     */
    public Product save(Product product) {
        return productRepository.save(product);
    }

    /**
     * 批量保存或更新产品
     *
     * @param products 产品
     */
    public void saveAll(List<Product> products) {
        productRepository.saveAll(products);
    }

    /**
     * 根据ID查询
     *
     * @param id 产品ID
     * @return 产品
     */
    public Optional<Product> findById(String id) {
        return productRepository.findById(id);
    }

    /**
     * 查询全部
     *
     * @return 产品集合
     */
    public Iterable<Product> findAll() {
        return productRepository.findAll();
    }

    /**
     * 根据ID删除
     *
     * @param id 产品ID
     */
    public void deleteById(String id) {
        productRepository.deleteById(id);
    }

    /**
     * 全部删除
     */
    public void deleteAll() {
        productRepository.deleteAll();
    }
}

其中值得注意的是,调用save()方法时,如果实体对象的id字段为null,Elasticsearch会自动生成一个文档ID并回填到返回的对象中;如果id已有值,则以该值作为文档ID,若文档已存在则执行全量更新。

方法名派生查询

与SpringData JPA类似,SpringData Elasticsearch支持通过方法名称自动推导查询逻辑,简单查询可以直接使用方法名派生查询,省去手写复杂QueryDSL的麻烦。下面例子中,我们针对text类型的产品名和产品描述设计了一个检索方法,SpringData Elasticsearch会自动生成对应的Match Query。

package com.gacfox.demo.repository;

import com.gacfox.demo.model.Product;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

import java.util.List;

public interface ProductRepository extends ElasticsearchRepository<Product, String> {
    List<Product> findByNameContainingOrDescriptionContaining(String name, String description);
}

这里由于findByNameContainingOrDescriptionContaining()是我们自己组装的,因此需要将其加入ProductRepository接口中,由于我们用了Or查询,SpringData Elasticsearch要求我们传入两个参数,不过在这个场景中这两个参数值是相同的。下面代码调用了我们创建的findByNameContainingOrDescriptionContaining()方法名派生查询。

package com.gacfox.demo.service;

import com.gacfox.demo.model.Product;
import com.gacfox.demo.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("productService")
public class ProductService {
    private final ProductRepository productRepository;

    @Autowired
    public ProductService(ProductRepository productRepository) {
        this.productRepository = productRepository;
    }

    public List<Product> queryProducts(String pattern) {
        return productRepository.findByNameContainingOrDescriptionContaining(pattern, pattern);
    }
}

Repository的方法名派生查询在底层会被解析并转换成特定的Query DSL,具体转化为哪种Query DSL是由SpringData Elasticsearch底层的规则定义的,转换结果不仅取决于方法名中的关键字,还很大程度上取决于实体类中字段的类型定义,以下是常见的方法名派生查询与Query DSL的转换规则映射表。

方法名关键字示例 字段类型 (FieldType) 对应 ES Query DSL 核心转换逻辑与说明
findByTitle(String s) text match text字段默认会被分词,传入的字符串s也会被分词然后进行全文检索。
findByTitle(String s) keyword / boolean / 各种数值类型 term 精确匹配,不会对输入值分词,必须完全一致。
findByTitleEquals(String s) 任何类型 同上(根据类型转 match 或 term) Equals是默认行为,与不加关键字效果相同。
findByTitleLike(String s)、findByTitleContains(String s) text match_phrase 在text字段上,框架会将其转化为倒排索引全文检索。
findByTitleLike(String s)、findByTitleContains(String s) keyword wildcard 在keyword字段上,框架会自动在参数前后拼接*执行通配符模糊查询(性能较差,生产环境慎用)。
findByTitleStartingWith(String s) keyword prefix或wildcard 类似Like但会尽可能优化为前缀查询。
findByAgeGreaterThan(int a)、findByAgeBefore(Date d) 各种数值类型 / date / keyword range (gt / lt) 范围查询。
findByAgeGreaterThanEqual(...) 各种数值类型 / date / keyword range (gte / lte) 带等号的范围查询。
findByTitleIn(Collection<String> c) 任何类型 terms 多值精确匹配。传入集合,只要字段值匹配集合中的任意一个term即可。
findByTitleActiveTrue() boolean term 状态快捷查询,匹配布尔类型字段为true的简化写法。
findByTitleIsNull() 任何类型 exists 检查字段是否存在(字段不存在或为null都被视为不存在),底层使用exists查询并取反。

ElasticsearchOperations

ElasticsearchOperations是SpringData Elasticsearch提供的核心操作接口,它对应于Elasticsearch的各种查询和操作API,通过这个接口我们能构建复杂的Query DSL,相比简单的方法名派生查询,ElasticsearchOperations适合需要精细控制查询行为的场景。

局部更新

Repository的save()方法是全量覆盖写入,如果只想更新某个字段,我们应当使用ElasticsearchOperations的UpdateQuery,避免其它字段被意外覆盖。

package com.gacfox.demo.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.UpdateQuery;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service("productService")
public class ProductService {
    private final ElasticsearchOperations elasticsearchOperations;

    @Autowired
    public ProductService(ElasticsearchOperations elasticsearchOperations) {
        this.elasticsearchOperations = elasticsearchOperations;
    }

    public void updateStock(String productId, int newStock) {
        Map<String, Object> params = new HashMap<>();
        params.put("stock", newStock);

        UpdateQuery updateQuery = UpdateQuery.builder(productId)
                .withDocument(Document.from(params))
                .build();
        elasticsearchOperations.update(updateQuery, IndexCoordinates.of("products"));
    }
}

全文检索

下面例子中,我们创建了一个在name字段上的全文检索查询,相比之前的方法名派生查询,这里我们直接使用代码构建了查询逻辑。SpringData Elasticsearch会自动注册ElasticsearchOperations的Bean,因此我们可以直接注入使用。

package com.gacfox.demo.service;

import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import com.gacfox.demo.model.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.client.elc.NativeQuery;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("productService")
public class ProductService {
    private final ElasticsearchOperations elasticsearchOperations;

    @Autowired
    public ProductService(ElasticsearchOperations elasticsearchOperations) {
        this.elasticsearchOperations = elasticsearchOperations;
    }

    public List<Product> queryProducts(String pattern) {
        Query query = Query.of(q ->
                q.match(m -> m
                        .field("name")
                        .query(pattern)
                )
        );

        NativeQuery nativeQuery = NativeQuery.builder()
                .withQuery(query)
                .build();
        SearchHits<Product> searchHits = elasticsearchOperations.search(nativeQuery, Product.class);
        return searchHits.stream()
                .map(SearchHit::getContent)
                .toList();
    }
}

SearchHits是查询结果的包装对象,每一条命中记录都会被封装为SearchHit<T>,通过getContent()我们可以得到反序列化后的实体对象,此外SearchHit上还可以使用getScore()获取相关度评分、使用getHighlightFields()获取高亮片段等信息。

带过滤条件查询

下面例子我们构建了一个带过滤条件的Bool Query,它会在指定范围内进行全文检索。

Query query = Query.of(q -> q
        .bool(b -> {
            b.must(m -> m.match(ma -> ma.field("name").query(keyword)));
            if (category != null) {
                b.filter(f -> f.term(t -> t.field("category").value(category)));
            }
            if (maxPrice != null) {
                b.filter(f -> f.range(r -> r.number(n -> n.field("price").lte(maxPrice))));
            }
            b.filter(f -> f.term(t -> t.field("is_deleted").value(false)));
            return b;
        })
);

分页查询

下面例子演示了分页查询的写法。

package com.gacfox.demo.service;

import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import org.springframework.data.domain.Page;
import com.gacfox.demo.model.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.client.elc.NativeQuery;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("productService")
public class ProductService {
    private final ElasticsearchOperations elasticsearchOperations;

    @Autowired
    public ProductService(ElasticsearchOperations elasticsearchOperations) {
        this.elasticsearchOperations = elasticsearchOperations;
    }

    public Page<Product> searchWithPage(String pattern, int page, int size) {
        Query query = Query.of(q -> q
                .match(m -> m.field("name").query(pattern))
        );

        NativeQuery nativeQuery = NativeQuery.builder()
                .withQuery(query)
                .withSort(s -> s.field(f -> f.field("price").order(SortOrder.Asc)))
                .withPageable(PageRequest.of(page, size))
                .build();
        SearchHits<Product> searchHits = elasticsearchOperations.search(nativeQuery, Product.class);
        List<Product> content = searchHits.stream()
                .map(SearchHit::getContent)
                .toList();
        return new PageImpl<>(content, PageRequest.of(page, size), searchHits.getTotalHits());
    }
}

withPageable()接收SpringData的Pageable对象,我们传入PageRequest.of(page, size)即可,注意page从0开始计数。至于返回的文档总数,可以通过searchHits.getTotalHits()获取。

高亮显示

全文检索场景中通常需要将搜索关键词在结果中高亮显示,Elasticsearch本身提供了HTML标签标注的高亮功能来实现这一需求,SpringData Elasticsearch对其进行了进一步封装。

package com.gacfox.demo.service;

import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import lombok.extern.slf4j.Slf4j;
import com.gacfox.demo.model.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.client.elc.NativeQuery;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.HighlightQuery;
import org.springframework.data.elasticsearch.core.query.highlight.Highlight;
import org.springframework.data.elasticsearch.core.query.highlight.HighlightField;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Service("productService")
public class ProductService {
    private final ElasticsearchOperations elasticsearchOperations;

    @Autowired
    public ProductService(ElasticsearchOperations elasticsearchOperations) {
        this.elasticsearchOperations = elasticsearchOperations;
    }

    public List<Product> search(String pattern) {
        Query query = Query.of(q -> q
                .match(m -> m.field("name").query(pattern))
        );

        NativeQuery nativeQuery = NativeQuery.builder()
                .withQuery(query)
                .withHighlightQuery(new HighlightQuery(
                        new Highlight(List.of(new HighlightField("name"))),
                        Product.class
                ))
                .build();

        SearchHits<Product> searchHits = elasticsearchOperations.search(nativeQuery, Product.class);
        List<Product> productList = new ArrayList<>();
        for (SearchHit<Product> hit : searchHits) {
            productList.add(hit.getContent());
            Map<String, List<String>> highlightFields = hit.getHighlightFields();
            log.info("highlightFields: {}", highlightFields);
        }
        return productList;
    }
}

高亮结果中会用<em>标签包裹匹配到的关键词片段,前端拿到后直接渲染即可。

聚合查询

下面例子中我们实现按品牌分组统计产品数量的逻辑。

package com.gacfox.demo.service;

import co.elastic.clients.elasticsearch._types.aggregations.Aggregation;
import co.elastic.clients.elasticsearch._types.aggregations.StringTermsAggregate;
import co.elastic.clients.elasticsearch._types.aggregations.StringTermsBucket;
import lombok.extern.slf4j.Slf4j;
import com.gacfox.demo.model.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchAggregations;
import org.springframework.data.elasticsearch.client.elc.NativeQuery;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service("productService")
public class ProductService {
    private final ElasticsearchOperations elasticsearchOperations;

    @Autowired
    public ProductService(ElasticsearchOperations elasticsearchOperations) {
        this.elasticsearchOperations = elasticsearchOperations;
    }

    public Map<String, Long> brandCount() {
        NativeQuery nativeQuery = NativeQuery.builder()
                .withQuery(q -> q.matchAll(m -> m))
                .withAggregation("brand_count", Aggregation.of(a -> a
                        .terms(t -> t.field("brand").size(20))
                ))
                .withMaxResults(0)
                .build();

        SearchHits<Product> searchHits = elasticsearchOperations.search(nativeQuery, Product.class);
        Map<String, Long> result = new HashMap<>();
        ElasticsearchAggregations aggregations = (ElasticsearchAggregations) searchHits.getAggregations();
        if (aggregations != null) {
            StringTermsAggregate brandTerms = aggregations.aggregationsAsMap()
                    .get("brand_count")
                    .aggregation()
                    .getAggregate()
                    .sterms();
            for (StringTermsBucket bucket : brandTerms.buckets().array()) {
                result.put(bucket.key().stringValue(), bucket.docCount());
            }
        }
        return result;
    }
}
作者:Gacfox
版权声明:本网站为非盈利性质,文章如非特殊说明均为原创,版权遵循知识共享协议CC BY-NC-ND 4.0进行授权,转载必须署名,禁止用于商业目的或演绎修改后转载。