-1

When using elasticsearch-dsl python api ,is there any way to pass a variable as key in filter . Please have a look in the code below.

from elasticsearch import Elasticsearch
from elasticsearch_dsl import Search

es_client = Elasticsearch(['http://10.220.3.40'], port='9200')
param1 = 'xyz'
s = Search(using=es_client, index="index1", doc_type="sampledoc").filter("term", Key=param1)

print("Query 1 :"+str(s.to_dict()))
key_varialble_name = 'Key2'
s = Search(using=es_client, index="index1", doc_type="sampledoc").filter("term", key_varialble_name=param1)
print("Query 2 :"+str(s.to_dict()))

Here ,the variable named 'key_varialble_name' has a value assigned as 'Key2'.

But when used inside the filter,that value is not getting replaced and as a result the term key is containing the variable name (i.e. 'key_varialble_name' ) instead of the variable value (i.e. 'Key2' ).

I do not have much knowledge on python.

Can anybody let me know if there is anyway to pass the variable value as key here ?

Soumen
  • 121
  • 1
  • 3
  • 14

2 Answers2

2

As Daniel suggested ,use pass a dictionary object here to pass the key value pair and it would work .Your changed code would like the following .

from elasticsearch import Elasticsearch
from elasticsearch_dsl import Search

es_client = Elasticsearch(['http://10.220.3.40'], port='9200')
param1 = 'xyz'
s = Search(using=es_client, index="index1", doc_type="sampledoc").filter("term", Key=param1)

print("Query 1 :"+str(s.to_dict()))
dictionary_variable = {"Key2":param1}

s = Search(using=es_client, index="index1", doc_type="sampledoc").filter("term", ** dictionary_variable)
print("Query 2 :"+str(s.to_dict()))
Ayan
  • 401
  • 1
  • 4
  • 10
1

You can use ** with a dictionary for this.

....filter("term", **{key_variable_name: param1})
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895