You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Data Elasticsearch请求追加类型致查询无结果,如何规避?

问题解答

原因分析

Elasticsearch 7.x版本已逐步废弃索引类型(_type),默认使用_doc作为唯一类型;而你用的Spring Data Elasticsearch 3.1.12.RELEASE版本,默认会把实体类的简单类名(首字母小写即lineitem)作为类型名,自动追加到请求路径里。

但你的目标索引items*要么没有lineitem这个类型,要么实际用的是ES7默认的_doc类型,所以带lineitem的请求路径匹配不到数据,移除后才能正常查询。

解决办法

方法一:显式指定实体类类型为_doc

直接修改LineItem类的@Document注解,添加type = "_doc"参数,让Spring Data Elasticsearch用ES7默认的类型名构建请求:

@Document(indexName = "items*", createIndex = false, type = "_doc")
public class LineItem {
    // 字段定义
}

方法二:通过ElasticsearchOperations手动构建请求

如果不想修改实体类注解,可以用ElasticsearchRestTemplate(或ElasticsearchOperations)手动构建查询,指定索引模式并忽略类型:

@Autowired
private ElasticsearchRestTemplate restTemplate;

public List<LineItem> queryAllItems() {
    NativeSearchQuery query = new NativeSearchQueryBuilder()
        .withQuery(QueryBuilders.matchAllQuery())
        .build();
    
    // 指定索引模式,不附加类型
    IndicesQuery indicesQuery = new IndicesQuery(query, "items*");
    SearchHits<LineItem> hits = restTemplate.search(indicesQuery, LineItem.class);
    
    return hits.stream().map(SearchHit::getContent).collect(Collectors.toList());
}

方法三:自定义仓库查询方法

在你的Elasticsearch仓库接口中,使用@Query注解自定义查询逻辑,或者直接调用底层客户端发送请求,避免自动追加类型名。

内容的提问来源于stack exchange,提问作者kembhootha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 03:37:53