0

In below code I'm facing KeyError, even though my syntax seems fine.

data = {'id': 20720}
query = '{"query":{"bool":{"must":[{"term":{"status.keyword":"Running"}},{"term":{"id":{id}}}],"filter":[{"term":{"status.keyword":"Running"}}]}}}'
print(query.format(**data))
Traceback (most recent call last):
  File ".\demo.py", line 3, in <module>
    print(query.format(**data))
KeyError: '"query"'

Here I'm formatting Elasticsearch query, I don't wanted to use replace string because I have to iterate it multiple time if data contains more field.

I'm expecting below output.

{"query":{"bool":{"must":[{"term":{"status.keyword":"Running"}},{"term":{"id":20720}}],"filter":[{"term":{"status.keyword":"Running"}}]}}}

Shiva
  • 3
  • 1

2 Answers2

0

You need to double your curly braces except the ones around the id variable

query = '{{"query":{{"bool":{{"must"... {{"term":{{"id":{id} }} }}...
Val
  • 207,596
  • 13
  • 358
  • 360
0

When you use single {} around some text and try to use format method, it expects all the attributes that are enclosed in {}. So if you look at the query string, the first { found is around query are we are only passing id to the format method. It's expecting query as well so that's why you are getting this error.

To resolve the issue, you need to wrap all key values in {{}} to escape the format method keyword arguments. You need to wrap only those values that you want to replace later on with single {} but all others should be wrapped around {{}}. Following is the fixed code.

data = {'id': 20720}
query = '{{"query":{{"bool":{{"must":[{{"term":{{"status.keyword":"Running"}}}},{{"term":{{"id":{id}}}}}],"filter": [{{"term":{{"status.keyword":"Running"}}}}]}}}}}}'
print(query.format(**data))

You will see following output: {"query":{"bool":{"must":[{"term":{"status.keyword":"Running"}},{"term":{"id":20720}}],"filter": [{"term":{"status.keyword":"Running"}}]}}}

Itezaz
  • 66
  • 3