2013-11-28 157 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

相關問題