且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何用弹性搜索中的数组元素进行搜索?

更新时间:2023-02-05 12:57:54

这是正确的用法,更新提示。



如果您导入带有提及数组的文档,则在匹配的数组项上进行搜索,将其称为提及,将检索该文档。我有同样的问题,现在就自己验证了。


I have a document indexed in elasticsearch:

{
    "content":"Some content with @someone mention",
    "mentions":["someone"],
    "userId":"4dff31eaf8815f4df04e2d62"
}

I try to find it with a query:

{
    "query": {
        "filtered": {
            "filter": { "term":{"userId":"4dff31eaf8815f4df04e2d62"} },
            "query": {
                term: {"mentions":"someone"}
            }
        }
    }
}

and receive no results.

In the same time query for content works fine:

{
    "query": {
        "filtered": {
            "filter": { "term":{"userId":"4dff31eaf8815f4df04e2d62"} },
            "query": {
                "term": {"content":"some"}
            }
        }
    }
}

Is some special syntax required for search through arrays? I found several topics [1, 2] about arrays in elasticsearch, but there is no direct answer.

UPD Get Mapping call returns the next result:

{
    "records": {
        "all":{
            "properties":{
                "content":{"type":"string"},
                "userId":{"type":"string"},
                "mentions":{"type":"string"}
            }
        }
    }
}

UPD2 I found the source of problem. I accidentally introduced an error into my question. The username I actually had in DB was in form "some_one" (underscore is significant). So standard index split it into 2 words and query for "some_one" of cause failing.

This is correct usage, as your update mentions.

If you import a document with a "mentions" array, searching on a matching array item, referring to it as "mentions", will retrieve the document. I had the same issue and verified it myself just now.