2013-11-28 113 views
1

对于电子商务,我正在实施elasticsearch以获得产品id的分类和分页结果集。根据过滤条件对elasicsearch结果集进行排序

我有一个产品的文件,看起来像这样:

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"}} 
    ] 
} 

然而,如何我现在了解到的要求是,产品分类取决于类别。看看上面的例子,这意味着我需要为类别数组中的每个值添加不同的排序值,并且取决于我要筛选的类别,我想按相应的排序值进行排序。

的文件应该是这个样子:

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"}} 
    ] 
} 

是它在某种程度上可以做到这一点?

回答

1

要做到这一点,您必须将类别存储为嵌套文档。如果不是,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 
       } 
      } 
     } 
    } 
} 
' 
+0

非常感谢您!那是我正在寻找的答案。 – user1036651

相关问题