【问题标题】:How can I get all results containing elasticsearch-dsl query keyword?如何获取包含 elasticsearch-dsl 查询关键字的所有结果?
【发布时间】:2021-02-17 09:27:37
【问题描述】:

当我查询我的 PostDocument 时,它返回的结果仅包含查询中的完整单词。例如,如果有 4 个帖子:

1. "Post 1"
2. "Post 2"
3. "Posts 3"
4. "Po 4"

我查询它:posts = PostDocument.search().query('match', body="Post") 它将返回项目 1 和 2,如果 body="Po" 它将仅返回项目 4。我如何编写查询以返回包含关键字的所有结果?例如,如果我这样做 body="Po" 我会得到所有 4 个项目。

【问题讨论】:

    标签: python django elasticsearch elasticsearch-dsl


    【解决方案1】:

    您可以使用edge_ngram tokenizer 首先将文本分解为 每当遇到指定字符列表中的一个时, 然后它发出每个单词的 N-gram,其中 N-gram 的开头是 锚定到单词的开头。

    添加一个包含索引数据、映射、搜索查询和搜索结果的工作示例

    索引映射:

    {
      "settings": {
        "analysis": {
          "analyzer": {
            "my_analyzer": {
              "tokenizer": "my_tokenizer"
            }
          },
          "tokenizer": {
            "my_tokenizer": {
              "type": "edge_ngram",
              "min_gram": 2,
              "max_gram": 10,
              "token_chars": [
                "letter",
                "digit"
              ]
            }
          }
        },
        "max_ngram_diff": 50
      },
      "mappings": {
        "properties": {
          "body": {
            "type": "text",
            "analyzer": "my_analyzer"
          }
        }
      }
    }
    

    索引数据:

    {
      "body": "Post 1"
    }
    {
      "body": "Post 2"
    }
    {
      "body": "Posts 3"
    }
    {
      "body": "Po 4"
    }
    

    搜索查询:

    {
        "query": {
            "match": {
                "body": "Po"
            }
        }
    }
    

    搜索结果:

    "hits": [
          {
            "_index": "64684245",
            "_type": "_doc",
            "_id": "4",
            "_score": 0.1424427,
            "_source": {
              "body": "Po 4"
            }
          },
          {
            "_index": "64684245",
            "_type": "_doc",
            "_id": "1",
            "_score": 0.10158265,
            "_source": {
              "body": "Post 1"
            }
          },
          {
            "_index": "64684245",
            "_type": "_doc",
            "_id": "2",
            "_score": 0.10158265,
            "_source": {
              "body": "Post 2"
            }
          },
          {
            "_index": "64684245",
            "_type": "_doc",
            "_id": "3",
            "_score": 0.088840574,
            "_source": {
              "body": "Posts 3"
            }
          }
        ]
    

    【讨论】:

    • 我将如何以pythonic方式编写查询?
    • @SLDem 抱歉,我不知道 python 代码 :( 但是在 JSON 格式的弹性搜索中,可以通过使用 edge_ngrams 来实现。如果对您有帮助,请不要忘记支持我的回答: )
    • @SLDem 如果您也能够使用 python 实现,那么请也接受我的回答:)
    • np 伴侣,是的,我有 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-25
    • 2017-08-25
    • 2012-04-19
    • 1970-01-01
    相关资源
    最近更新 更多