对于电子商务,我正在实现elasticsearch以便获得类别的产品ID的排序和分页结果集。
我有一个产品文档,如下所示:
PUT /products_test/product/1
{
"id": "1",
"title": "foobar",
"sort": 102,
"categories": [
"28554568",
"28554577",
"28554578"
],
}
为了得到结果集,我进行了过滤和排序:
POST /products/_search
{
"filter": {
"term": {
"categories": "28554666"
}
},
"sort" : [
{ "sort" : {"order" : "asc"}}
]
}
但是,我现在了解的要求是,产品分类取决于类别。查看上面的示例,这意味着我需要为Categories数组中的每个值添加一个不同的排序值,并取决于我要根据相应的排序值进行排序的类别。
该文档应如下所示:
PUT /products_test/product/1
{
"id": "1",
"title": "foobar",
"categories": [
{ "id": "28554568", "sort": "102" },
{ "id": "28554577", "sort": "482" },
{ "id": "28554578", "sort": "2" }
]
}
我的查询现在应该可以对以下内容进行排序:
POST /products/_search
{
"filter": {
"term": {
"categories.id": "28554666"
}
},
"sort" : [
{ "categories.{filtered_category_id}.sort" : {"order" : "asc"}}
]
}
是否有可能做到这一点?
最佳答案
为此,您必须将类别存储为嵌套文档。如果不是,Elasticsearch将不知道哪种类别与什么类别ID相关联。
然后,您将必须对嵌套文档进行排序,还必须进行过滤以选择正确的文档。
这是一个可运行的示例,您可以使用:https://www.found.no/play/gist/47282a07414e1432de6d
curl -XPUT "$ELASTICSEARCH_ENDPOINT/play" -d '{
"mappings": {
"type": {
"properties": {
"categories": {
"type": "nested"
}
}
}
}
}'
curl -XPOST "$ELASTICSEARCH_ENDPOINT/_bulk?refresh=true" -d '
{"index":{"_index":"play","_type":"type"}}
{"id":1,"title":"foobar","categories":[{"id":"28554568","sort":102},{"id":"28554577","sort":482},{"id":"28554578","sort":2}]}
{"index":{"_index":"play","_type":"type"}}
{"id":2,"title":"barbaz","categories":[{"id":"28554577","sort":0}]}
'
curl -XPOST "$ELASTICSEARCH_ENDPOINT/_search?pretty" -d '
{
"query": {
"nested": {
"path": "categories",
"query": {
"term": {
"categories.id": {
"value": 28554577
}
}
}
}
},
"sort": {
"categories.sort": {
"order": "asc",
"nested_filter": {
"term": {
"categories.id": 28554577
}
}
}
}
}
'
关于sorting - 根据过滤条件对Elasticsearch结果集进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20269035/