Search code examples
pythondjangoelasticsearchelasticsearch-dsl

How to make true query in django_elasticsearch_dsl like icontains in django?


Need using django_elasticsearch_dsl search by given text. It should works as for full word and for only part of world. Like for "Example" and "xample". Using python 3.6, django_elasticsearch_dsl 7.0

Have found in documentation that django "icontains" query is similar to "match_phrase" in elasticsearch_dsl.query, but seems it does not work for me.

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'])
 )

Does not work for part of word (ex. "neve", full is "never") But Django query works good

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

Use only one field to filter by just for example

I expect to find something looks like django icontains filter. Need to find not only for full word match.


Solution

  • Try with regex:

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