NativeSearchQuery returns 即使在将单个标识符作为查询的一部分传递时也会有所有结果

NativeSearchQuery returns all results even when passing a single identifier as part of query

List<String> ids = List.of(id);

NativeSearchQuery query = new NativeSearchQueryBuilder()
    .withSourceFilter(new FetchSourceFilterBuilder().withIncludes(section).build())
    .withIds(ids)
    .build();
log.trace("query {}", query.toString());

SearchHits<Foo> searchHits = operations.search(query, Foo.class, index);

上面的代码片段生成了以下查询,但不清楚为什么当我已经明确提到使用单个 id 使用 withIds(ids)

时它会获取所有 Foos
Sending request POST /foos/_search?typed_keys=true&max_concurrent_shard_requests=5&ignore_unavailable=false&expand_wildcards=open&allow_no_indices=true&ignore_throttled=true&search_type=dfs_query_then_fetch&batched_reduce_size=512&ccs_minimize_roundtrips=true with parameters: 

Request body: {"from":0,"size":10000,"version":true,"_source":{"includes":["bp"],"excludes":[]}}

2021-01-15 10:12:45.075 TRACE 45572 --- [/O dispatcher 1] o.s.data.elasticsearch.client.WIRE       : [6ba88ad6] Received raw response: 200 OK

2021-01-15 10:12:45.284 TRACE 45572 --- [nio-5555-exec-2] c.p.matrimony.service.BaseService        : searchHitsConvertList input SearchHits{totalHits=235, totalHitsRelation=EQUAL_TO, maxScore=1.0, scrollId='null', searchHits={235 elements}, aggregations=null}

withIds() 用于其他上下文(即通过 _mget 按 ID 检索多个文档时)。

在你的情况下,你应该简单地进行一些不同的处理,即在 _id 字段上使用 terms 过滤器:

NativeSearchQuery query = new NativeSearchQueryBuilder()
    .withSourceFilter(new FetchSourceFilterBuilder().withIncludes(section).build())
    .withFilter(QueryBuilders.termsFilter("_id", ids))
    .build();