首页 > 解决方案 > 如何在 django_elasticsearch_dsl 中像 django 中的 icontains 一样进行真正的查询?

问题描述

需要使用 django_elasticsearch_dsl 搜索给定的文本。它应该适用于完整的单词并且仅适用于世界的一部分。就像“示例”和“示例”一样。使用 python 3.6,django_elasticsearch_dsl 7.0

在文档中发现 django“icontains”查询类似于 elasticsearch_dsl.query 中的“match_phrase”,但似乎对我不起作用。

titles = TitleDocument.search().query(
            Q("match", title=kwargs['text']) or
            Q("match", slug=kwargs['text']) or
            Q("match", page_title=kwargs['text']) or
            Q("match_phrase", menu_title=kwargs['text']) or
            Q("match_phrase", meta_description=kwargs['text'])
 )

不适用于部分单词(例如“neve”,full 是“never”)但 Django 查询效果很好

ti = Title.objects.filter(meta_description__icontains=kwargs['text'])

仅使用一个字段进行过滤,例如

我希望找到一些看起来像 django icontains 过滤器的东西。不仅需要查找全词匹配。

标签: pythondjangoelasticsearchelasticsearch-dsl

解决方案


尝试使用正则表达式:

text = ".*{}.*".format(kwargs["text"])
titles = TitleDocument.search().query(
    "query_string",
    query=text,
    fields=["title", "slug", "page_title", "menu_title", "meta_description"],
)

推荐阅读