文章目录
  1. 1. 问题
  2. 2. 场景
  3. 3. 功能实现
  4. 4. 参考链接

问题

此文关于 ElasticSearch 中 nested 类型中某个字段排序的问题。

场景

以官方数据模型为例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
PUT /my_index/blogpost/2
{
"title": "Investment secrets",
"body": "What they don't tell you ...",
"tags": [ "shares", "equities" ],
"comments": [
{
"name": "Mary Brown",
"comment": "Lies, lies, lies",
"age": 42,
"stars": 1,
"date": "2014-10-18"
},
{
"name": "John Smith",
"comment": "You're making it up!",
"age": 28,
"stars": 2,
"date": "2014-10-16"
}
]
}

从以上结构能看出,每片文章有很多评论,评论是 nested 类型。业务的场景是:将评论中 starts 为 2的,按照年龄从高到低,对所有的文章进行排序。

功能实现

废话不多说直接上代码:

1
2
3
4
5
6
7
SortOrder sortOrder = SortOrder.DESC;
int stars = 2;
// String flag = sortOrder.toString().equals("desc") ? "_last" : "_first";
SortBuilder sortBuilder = SortBuilders.fieldSort("comments.age")
.setNestedFilter(termQuery("comments.stars", stars)).setNestedPath("comments").order(sortOrder);//.missing(flag).unmappedType("long");

requestBuilder.addSort(sortBuilder);

以上代码中,针对 nested 类型的排序,setNestedPath() 和 setNestedFilter() 两个方法是必须的。其中 setNestedFilter() 的参数 QueryBuilder 的过滤字段,path 是必须要有的(2.1版本亲测),即 “comments.stars”。

Restful 格式如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
"from" : 0,
"size" : 20,
"sort" : [ {
"comments.age" : {
"order" : "desc",
"nested_filter" : {
"term" : {
"comments.stars" : 2
}
},
"nested_path" : "comments"
}
} ]
}

参考链接

本文参考的链接如下:

官方网站: https://www.elastic.co/guide/en/elasticsearch/guide/current/nested-sorting.html


本文地址 http://94275.cn/2017/03/11/elasticsearch-sort-nested/ 作者为 Zhenguo

author:Zhenguo
Author: Zhenguo      Blog: 94275.cn/     Email: jinzhenguo1990@gmail.com
I have almost 10 years of application development experience and have a keen interested in the latest emerging technologies. I use my spare time to turn my experience, ideas and love for IT tech into informative articles, tutorials and more in hope to help others and learn more.
文章目录
  1. 1. 问题
  2. 2. 场景
  3. 3. 功能实现
  4. 4. 参考链接
返回顶部