Search code examples
pythonquery-stringelasticsearch-dsl

How to use query_string (Lucene Syntax) with Elasticsearch DSL in Python?


I want to use the query_string (Lucene Syntax) search with Elasticsearch DSL for Python. Unfortunately the first line doesn't work as easy as the second one:

s = Search(using=client, index='abc').query("query_string", doctext=searchstr).highlight('doctext', fragment_size=200)
s = Search(using=client, index='abc').query("match", doctext=searchstr).highlight('doctext', fragment_size=200)

Which function of the Elasticsearch DSL library could I use for query_string?


Solution

  • You can use query_string but you need to use the proper parameters it defines in documentation:

    s = Search(using=client, index='abc')
    s = s.query("query_string", query=searchstr, default_field="doctext") # note the query here
    s = s.highlight('doctext', fragment_size=200)
    

    Also please note that using query_string for input provided by users can be dangerous as there is no way to restrict what users can do in the query and they can potentially query against any field or craft a super expensive query that will be costly to execute.

    Hope this helps!