簡體   English   中英

如何在Elasticsearch中按文檔數組中的多個對象字段進行查詢?

[英]How to query by multiple fields of object in array of a document in Elasticsearch?

大家好,我是 Elasticsearch 的新手。 我想通過其字段(類型:數組)的值來查詢文檔。 像這樣的例子:

docx=people:[
{id:1,role:admin},
{id:2,role:other}
]
docy=people:[
{id:1,role:other},
{id:2,role:admin}
]

我的查詢是people.id:1 AND people.role:admin 我的預期結果只是 docx,但 ES 也返回 docy。 我知道這是錯誤的,但我怎么能在 ES 中做到這一點。 那么查詢字符串如何才能僅過濾像 docx 這樣的文檔。 謝謝!

您需要在您的情況下使用嵌套數據類型,因為對象數據類型被展平並單獨處理,這導致兩個文檔都匹配結果,將添加一個工作示例。

但是請注意,當您擁有大型數據集和大量並發查詢時,嵌套數據類型會變得昂貴,如go-jek 的中型博客中所述。

請關注博客,其中詳細介紹了您的問題。

具有正確映射的工作示例

索引映射

{
    "mappings": {
        "properties": {
            "name" : {
             "type" :   "text"
            },
            "people": {
                "type": "nested"
            }
        }
    }
}

索引示例文檔

{
    "name": "bar",
    "people": 
    [
        {
            "id": 1,
            "role": "other"
        },
        {
            "id": 2,
            "role": "admin"
        }
    ]
}

和第二個示例文檔

{
    "name": "foo",
    "people": 
    [
        {
            "id": 1,
            "role": "admin"
        },
        {
            "id": 2,
            "role": "other"
        }
    ]
}

搜索查詢

{
    "query": {
        "nested": {
            "path": "people",
            "query": {
                "bool": {
                    "must": [
                        {
                            "match": {
                                "people.id": 1
                            }
                        },
                        {
                            "match": {
                                "people.role": "admin"
                            }
                        }
                    ]
                }
            }
        }
    }
}

和預期的搜索結果

"hits": [
            {
                "_index": "matchphrase",
                "_type": "_doc",
                "_id": "1",
                "_score": 1.6931472,
                "_source": {
                    "name": "foo",
                    "people": [
                        {
                            "id": 1,
                            "role": "admin"
                        },
                        {
                            "id": 2,
                            "role": "other"
                        }
                    ]
                }
            }
        ]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM