-1

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 ?

3
  • Maybe you should elaborate the question. Are you concerned about NoSQL injection ?, or wan't to do prefix search ? Commented Jun 23, 2020 at 8:38
  • Do you have your query in a variable? Commented Jun 23, 2020 at 10:01
  • Yes. the search string is stored in a variable and I want to create a query with that string. Basically user should get results corresponding to the input given by him/her. Obviously I cannot write a static query. How should I proceed? Commented Jun 23, 2020 at 10:17

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

7 Comments

I am thinking of using a regexp instead of wildcard for writing an easier query. Is this the correct way of writing an expression? result = es.search(index="my-index", body="{\"query\" : {\"regexp\": {\"Name\": \" "+str+".*\" }}})"
You just need to replace wildcard by regexp
Thanks. The solution worked. But I have another problem (hopefully the last one) at hand. The regex should contain another dynamic variable- the number of characters that should occur before string matching starts.
For example a working query that I wrote was something like this : "[a-z]{2}"+searchWord+".*" Here I'm anchoring my searchWord in such a way that it appears as a substring starting from exactly the 3rd character (beginning 2 chars can be anything). How should I formulate the above query with "2" also being an input variable?
Of Course. My bad. should've typecast int to string. Thanks a lot. You've solved a lot of my problems.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.