解決此問題的最佳方法可能是利用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