Search code examples
elasticsearchspring-data-elasticsearch

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);

The above code snippet, generates the following query but its not clear why its fetching all Foos when I have clearly mentioned to use a single id using withIds(ids)

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}

Solution

  • withIds() is used in another context (i.e. when retrieving multiple documents by ID via _mget).

    In your case, you should simply proceed a bit differently, i.e. with a terms filter on the _id field:

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