Search code examples
pythonelasticsearchwildcardelasticsearch-dslelasticsearch-query

Python : wildcard query in Elasticsearch


I want to query a field using wildcard in Elasticsearch but the problem is that the search string is stored in a variable and not available statically. The intended query is :

body={"query": {"wildcard": {"Name": { "value" : "Vi?????" }}}}

where the search string "Vi" is not available at compile time. It will be given by user. Say it is stored in some variable str (= "Vi"). How should I formulate a query using str and "?"s ?


Solution

  • You have to use + concatenation in python.

    And you need to escape double quotes. There are many ways to do this. I prefer escaping double quotes as \"

    searchWord ="Vi";
    query = "{\"query\": {\"wildcard\": {\"Name\": { \"value\" : \"" + searchWord + "?????\" }}}}";
    print (query);
    

    searchWord is something that you receive from the user. I hardcoded it.

    query is the one you need to form. This is how I formed it \"" + searchWord + "?????\"

    Please check and provide any information which I need to consider.

    EDIT:

    searchWord ="Vi";
    x = 2;
    query = "{\"query\": {\"wildcard\": {\"Name\": { \"value\" : \"" + "[a-z]{" + str(x) +"}" + searchWord + "?????\" }}}}";
    print (query);