当前位置: 首页 > elasticsearch, 搜索 > 正文

elasticsearch应用:addPartialField函数过滤

1 星2 星3 星4 星5 星 (1 次投票, 评分: 5.00, 总分: 5)
Loading ... Loading ...
baidu_share

在实际项目中,有如下需求,图片字段不为空的返回。在elasticsearch中要用到addPartialField函数。其源码如下:

1
2
3
4
5
6
7
8
9
10
11
12
    /**
     * Adds a partial field based on _source, with an "include" and/or "exclude" set which can include simple wildcard
     * elements.
     *
     * @param name    The name of the field
     * @param include An optional include (optionally wildcarded) pattern from _source
     * @param exclude An optional exclude (optionally wildcarded) pattern from _source
     */
    public SearchRequestBuilder addPartialField(String name, @Nullable String include, @Nullable String exclude) {
        sourceBuilder().partialField(name, include, exclude);
        return this;
    }

再实际应用中如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
 
client.prepareIndex("test", "type1", "1").setSource(XContentFactory.jsonBuilder().startObject()
 
                .field("field1", "value1")
 
                .startObject("obj1")
 
                .startArray("arr1")
 
                .startObject().startObject("obj2").field("field2", "value21").endObject().endObject()
 
                .startObject().startObject("obj2").field("field2", "value22").endObject().endObject()
 
                .endArray()
 
                .endObject()
 
                .endObject())
259	
                .execute().actionGet();
 
 
SearchResponse response = client.prepareSearch("test")
 
                .addPartialField("partial1", "obj1.arr1.*", null)
 
 
 
                .execute().actionGet();

其中关键段为:

1
2
 .addPartialField("partial1", "obj1.arr1.*", null)
表示过滤掉为null的记录

本文固定链接: http://www.chepoo.com/elasticsearch-add-partial-field-demo.html | IT技术精华网

elasticsearch应用:addPartialField函数过滤:等您坐沙发呢!

发表评论