如何仅返回选定的字段

问题描述 投票:0回答:1

我需要一个查询,其中我仅选择 1 个字段,而不是整个文档。 我该怎么做?

我有这样的疑问:

NativeQuery query = NativeQuery
        .builder()
        .withMaxResults(100)
        .withQuery(...))
        .withFields("the_field_i_need")
        .build();

SearchHits<T> searchHits = operations.search(query, MyEntity.class, "my-index");

但我不知道如何返回字段“the_field_i_need”并忽略所有其他字段

java elasticsearch spring-data spring-data-elasticsearch
1个回答
0
投票

如果您只想检索特定字段而不是整个文档,可以使用 FetchSourceFilter 来包含或排除字段。以下是修改代码的方法:

import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;

// ...

NativeSearchQuery query = new NativeSearchQueryBuilder()
        .withQuery(...)  // Add your query here
        .withMaxResults(100)
        .withSourceFilter(new FetchSourceFilter(new String[]{"the_field_i_need"}, null))
        .build();

SearchHits<MyEntity> searchHits = elasticsearchRestTemplate.search(query, MyEntity.class, IndexCoordinates.of("my-index"));

在此示例中,FetchSourceFilter 用于指定要包含的字段(“the_field_i_need”)和排除(在本例中为 null,表示不排除任何字段)。生成的 SearchHits 将包含仅具有指定字段的文档。

© www.soinside.com 2019 - 2024. All rights reserved.