2015-08-14 61 views
0

我有後續的文檔之間的關係處理:彈性搜索 - 如何兩個文件

{"id":1 , "user_id":1234, "tags":["b"]} 
{"id":2 , "user_id":1234, "tags":["a"]} 
{"id":3 , "user_id":1236, "tags":["b"]} 
{"id":4 , "user_id":1237, "tags":["b"]} 
{"id":5 , "user_id":1238, "tags":["a"]} 
{"id":6 , "user_id":1239, "tags":["b"]} 

,我希望得到的是有沒有「一」中的「標籤」的所有users_id。

1236,(id =3) 
1237,(id =4) 
1239,(id =6) 

我不想得到1234,(id = 1),因爲他在另一個文檔的「標籤」中有「a」。 我試圖用聚合(搜索和嘗試)處理這個問題,但無法解決。

你知道如何解決這個問題嗎? 感謝您的閱讀。 最好的問候! :) PS:我使用java api來查詢我的數據,但您可以隨意使用DSL(json)。

回答

0

解決此問題的最佳方法可能是利用parent/child relationship

爲了測試它,我建立了一個指數有兩個映射,一個父類"user",一個是孩子式"user_tag"

PUT /test_index 
{ 
    "mappings": { 
     "user": { 
     "_id": { 
      "path": "user_id" 
     }, 
     "properties": { 
      "user_id": { 
       "type": "string" 
      } 
     } 
     }, 
     "user_tag": { 
     "_parent": { 
      "type": "user" 
     }, 
     "properties": { 
      "tags": { 
       "type": "string" 
      } 
     } 
     } 
    } 
} 

然後我翻譯你爲這種格式提供的數據(你可能有它盯着一點點說服自己,這是相同的數據):

POST /test_index/_bulk 
{"index":{"_type":"user"}} 
{"user_id":1234} 
{"index":{"_type":"user_tag","_parent":1234,"_id":1}} 
{"tags":["b"]} 
{"index":{"_type":"user_tag","_parent":1234,"_id":2}} 
{"tags":["a"]} 
{"index":{"_type":"user"}} 
{"user_id":1236} 
{"index":{"_type":"user_tag","_parent":1236,"_id":3}} 
{"tags":["b"]} 
{"index":{"_type":"user"}} 
{"user_id":1237} 
{"index":{"_type":"user_tag","_parent":1237,"_id":4}} 
{"tags":["b"]} 
{"index":{"_type":"user"}} 
{"user_id":1238} 
{"index":{"_type":"user_tag","_parent":1238,"_id":5}} 
{"tags":["a"]} 
{"index":{"_type":"user"}} 
{"user_id":1239} 
{"index":{"_type":"user_tag","_parent":1239,"_id":6}} 
{"tags":["b"]} 

現在我能得到沒有包含標籤"a"使用以下查詢一個孩子誰的用戶:

POST /test_index/user/_search 
{ 
    "query": { 
     "filtered": { 
     "filter": { 
      "not": { 
       "filter": { 
        "has_child": { 
        "type": "user_tag", 
        "filter": { 
         "term": { 
          "tags": "a" 
         } 
        } 
        } 
       } 
      } 
     } 
     } 
    } 
} 

返回:

{ 
    "took": 3, 
    "timed_out": false, 
    "_shards": { 
     "total": 1, 
     "successful": 1, 
     "failed": 0 
    }, 
    "hits": { 
     "total": 3, 
     "max_score": 1, 
     "hits": [ 
     { 
      "_index": "test_index", 
      "_type": "user", 
      "_id": "1236", 
      "_score": 1, 
      "_source": { 
       "user_id": 1236 
      } 
     }, 
     { 
      "_index": "test_index", 
      "_type": "user", 
      "_id": "1237", 
      "_score": 1, 
      "_source": { 
       "user_id": 1237 
      } 
     }, 
     { 
      "_index": "test_index", 
      "_type": "user", 
      "_id": "1239", 
      "_score": 1, 
      "_source": { 
       "user_id": 1239 
      } 
     } 
     ] 
    } 
} 

這是我使用的所有代碼:

http://sense.qbox.io/gist/66ca479e994d54257ec8cea86a5acf621a5c8c06