python - 如何获取所有包含elasticsearch-dsl查询关键字的结果?

标签 python django elasticsearch elasticsearch-dsl

当我查询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个项目。

最佳答案

You can use the edge_ngram tokenizer first breaks text down into words whenever it encounters one of a list of specified characters, then it emits N-grams of each word where the start of the N-gram is anchored to the beginning of the word.


添加带有索引数据,映射,搜索查询和搜索结果的工作示例
索引映射:
{
  "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"
        }
      }
    ]

关于python - 如何获取所有包含elasticsearch-dsl查询关键字的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64684245/

相关文章:

Python - 打印出对特定实例的所有引用

javascript - Scrapy获取javascript的空白页

indexing - 多语言 ElasticSearch 支持

python - 分割字典的键 (12-13-14) 并找到最小的数字

python - 什么是 python 字符串?

Django Rest Framework View get_queryset 被调用两次

python - Django 休息框架版本控制

elasticsearch - Elasticsearch-按嵌套的多字段排序

elasticsearch - Kibana脚本字段

python - 从使用 React 的网站获取所有 HTML 代码