ElasticSearch匹配整个文档

时间:2019-09-22 12:38:51

标签: elasticsearch

我有一个这样的索引:

"mappings": {
    "_doc": {
        "properties": {
            "key_words": {"type": "text", "analyzer": "english", "search_analyzer": "english", "index": True},
            "name": {"type": "text", "index": False},
        }
    }

此索引包含主题名称和关键字,应进行匹配以使该主题与某些文本相关。因此,我需要使用长文本按主题索引进行搜索,并找到所有具有完全匹配项的主题。例如,如果我在索引中包含以下主题:

{"name": "a", "key_words": "World cup"}
{"name": "b", "key_words": "Gaming cup"}
{"name": "c", "key_words": "Cup"}

和文字:

The World Championship, some country win the Cup on tennis!

由于文本中存在文档中的所有关键字,因此我想使用“文本”进行查询,该文本仅与“ a”和“ c”文档匹配。

有人可以帮助我建立此查询吗? ES版本:6.8

1 个答案:

答案 0 :(得分:1)

感谢Jaspreet Chahal在评论中的链接,我在那里找到了解决方案。 我更改了映射,使其开始看起来像这样:

{
"mappings": {
    "_doc": {
        "properties": {
            "key_words": {"type": "text", "analyzer": "english", "search_analyzer": "english", "index": True, "fielddata": True},
            "name": {"type": "text", "index": False},
        }
    }
}

}

,我需要在两次调用中进行搜索,首先是分析文本并生成 令牌

analyzed = await el.indices.analyze(body={"analyzer": "english", "text": "The World Championship, some country win the Cup on tennis!"})

然后是具有脚本条件的呼叫

{
        "query": {
            "bool": {
                "must": [{
                    "match": {
                        "key_words": desc
                    }}],
                "filter": {
                    "script": {
                        "script": {
                            "source": "if(params.search_tokens.containsAll(doc['key_words'].values)){return true;}",
                            "lang": "painless",
                            "params": {
                                "search_tokens": [an['token'] for an in analyzed['tokens']]
                            }
                        }
                    }
                }
            }

        },
        "_source": ["_id"]
    }
相关问题