使用spring data elasticsearch仅查询并返回特定的嵌套字段

时间:2017-01-24 16:08:48

标签: spring-data-elasticsearch

是否可以使用spring data elasticsearch返回所有弹性文档文档的特定嵌套字段?

E.g。 es数据存储库将如何查找以下查询?

网址:/ myIndex / MyType / _search

查询正文:

{
  "_source": [
    "MyNestedObj.myField"
  ]
}

1 个答案:

答案 0 :(得分:0)

适用于Spring Elasticsearch数据> =版本2.0

不幸的是,版本1.x

无法使用源过滤
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.FetchSourceFilter;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SourceFilter;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;

@Repository
public class MyRepository {

    private final static String FIELD_MYFIELD = "MyNestedObj.myField";

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    public List<String> findAll() {
        SourceFilter sourceFilter = new FetchSourceFilter(new String[]{FIELD_MYFIELD}, null);
        final PageRequest pageRequest = new PageRequest(0, Integer.MAX_VALUE, new Sort(FIELD_MYFIELD));

        final NativeSearchQuery query = new NativeSearchQueryBuilder()//
                .withQuery(new MatchAllQueryBuilder()).withSourceFilter(sourceFilter)//
                .withIndices("myIndex").withTypes("MyType").withPageable(pageRequest)//
                .build();

        return this.elasticsearchTemplate.query(query, response -> {
            List<String> values = new ArrayList<>();
            final SearchHits hits = response.getHits();
            for (final SearchHit hit : hits) {
                values .add(hit.getSource().get(FIELD_MYFIELD));
            }
            return values;
        });
    }
}