通过 spring 数据从 elasticsearch 中获取一个字段 [英] get one field from elasticsearch by spring data

查看:46
本文介绍了通过 spring 数据从 elasticsearch 中获取一个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的 ES 文档

I have a ES Document like this

class User {
    String name;
    String describe;
    List<String> items;
}

我正在使用 spring 数据通过 Repository 接口与 ES 对话

I'm using spring data to talk to ES by the Repository interface

interface UserRepository extends Repository<User, String> {
}

现在我需要构建一个rest接口来响应这样的JSON格式数据

Now I need to build a rest interface which responses a JSON-format data like this

{"name": String, "firstItem": String}

因为User中的describeitems非常大,所以从ES中检索所有字段的成本非常高.

Because the describe and items in User is very big, it's very expensive to retrieve all field from the ES.

我知道 ES 有一个名为响应过滤"的功能,可以满足我的要求,但我没有找到在 Spring Data 中使用它的方法.

I know the ES have a feature named "Response Filtering" which can fit my requirement, but I don't find a way to using it in Spring Data.

如何在 spring 数据中执行此操作?

How to do this in spring data?

推荐答案

你需要的是 源过滤(用于不检索重字段)和响应过滤(用于不返回重字段).但是,后者在 Spring Data ES 中不支持(目前)

What you need is a mix of source filtering (for not retrieving heavy fields) and response filtering (for not returning heavy fields). However, the latter is not supported in Spring Data ES (yet)

对于前者,您可以利用 NativeSearchQueryBuilder 并指定一个 FetchSourceFilter 来仅检索您需要的字段.Spring Data ES 尚不支持后者.您可以做的是创建另一个名为 firstItem 的字段,您将在其中存储 items 的第一个元素,以便您可以为此查询返回它.

For the former, you can leverage NativeSearchQueryBuilder and specify a FetchSourceFilter that will only retrieve the fields you need. The latter is not supported yet in Spring Data ES. What you can do is to create another field named firstItem in which you'd store the first element of items so that you can return it for this query.

private ElasticsearchTemplate elasticsearchTemplate;

String[] includes = new String[]{"name", "firstItem"};
SearchQuery searchQuery = new NativeSearchQueryBuilder()
    .withQuery(matchAllQuery())
    .withSourceFilter(new FetchSourceBuilder(includes, null))
    .build();

Page<User> userPage =
    elasticsearchTemplate.queryForPage(searchQuery, User.class);

这篇关于通过 spring 数据从 elasticsearch 中获取一个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆