仅返回弹性搜索本机查询 Java api 中的特定字段 [英] Only return specific fields in elastic search native query Java api

查看:46
本文介绍了仅返回弹性搜索本机查询 Java api 中的特定字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建本机查询,但我只想返回某些字段,所有这些字段都保存在父字段中.我想我正在寻找与 REST API 的 _source 等效的 QueryBuilders 或 NativeSearchQueryBuilder.这是一个代码示例:

I'm building a native query but I only want to return certain fields, all of which are held within a parent field. I think I am looking for the QueryBuilders or NativeSearchQueryBuilder equivalent of the REST API's _source. Here's a code example:

NativeSearchQueryBuilder sb = new NativeSearchQueryBuilder()
.withIndices("myIndex")
.withTypes("myType")
.withQuery(QueryBuilders.queryStringQuery("parent.field2:Foo*"));
.withFields("parent.field1");

我希望这仅返回与具有 parent.field2 的对象(如 Foo*)相关联的 parent.field1 的列表.但它什么都不返回.

I'd expect this to return a list of only parent.field1 that are associated with objects that have parent.field2 like Foo*. But it returns nothing.

感谢您的帮助!

推荐答案

经过一番研究,我发现答案在 NativeSearchQueryBuilder.我只是使用旧版本的spring-data弹性搜索,所以我看不到这个方法:withSourceFilter.这样做的方法是:

After some research, I found the answer is in NativeSearchQueryBuilder. I was just using an older version of spring-data elastic search, so I could not see this method: withSourceFilter. The way to do this is:

NativeSearchQueryBuilder sb = new NativeSearchQueryBuilder()
.withIndices("myIndex")
.withTypes("myType")
.withQuery(QueryBuilders.queryStringQuery("parent.field2:Foo*"));
.withSourceFilter(new FetchSourceFilter(<String array of includes>, null));

FetchSourceFilter 接受 2 个参数,一个 String[] 包含数组和一个排除数组.在我的示例中,我将像 new String[]{"parent.field1"} 这样的数组传递给 FetchSourceFilter,后者又传递给 withSourceFilter.然后上面的搜索将返回(一旦构建并运行)一个 parent.field1 和 parent.field2 的列表,如 Foo*.

FetchSourceFilter takes 2 arguments, a String[] array of includes and one of excludes. In my example, I'd have an array like new String[]{"parent.field1"} passed to FetchSourceFilter, which in turn is passed to withSourceFilter. The search above will then return (once built and ran) a list of parent.field1 with parent.field2 like Foo*.

我升级到的版本是 spring-data-elasticsearch 2.0.2.

The version I upgraded to was spring-data-elasticsearch 2.0.2.

这篇关于仅返回弹性搜索本机查询 Java api 中的特定字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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