0

I need to build a Elasticsearch query inside a python script. In the Elasticsearch query I need to pass external python variable value to search.

Below is the python script which I have tried my self. But it doesn't take external variable parameter and when I set the value inside the query manually it works fine.

import master
mst = master.Master()

sourceip = "192.168.1.1" // External variable and its value

get_query_result = mst.build_query('{"query": {"bool": {"must": [{"match": { "source": "server_one" }},{"match": {"srcip": sourceip }}],"filter":[ {"range" : {"timestamp" :{"gte": "now-1d", "lte": "now"}}}]}}}')

total_query_result = get_query_result['hits']['total']

print(total_query_result)

When I put sourceip variable inside the elasticsearch query, it doesn't take the variable value and generate the result. It is raising an error

But When I set IP address value manually inside the Elasticsearch query, script return result successfully.

How to I pass python variable inside the Elasticsearch Query.

tharu85
  • 3
  • 1
  • 3

2 Answers2

2

You need to do it like this:

sourceip = "192.168.1.1"

query = '{"query": {"bool": {"must": [{"match": { "source": "server_one" }},{"match": {"srcip": "%s" }}],"filter":[ {"range" : {"timestamp" :{"gte": "now-1d", "lte": "now"}}}]}}}' % (sourceip)

get_query_result = mst.build_query(query)
Val
  • 207,596
  • 13
  • 358
  • 360
0

You need to insert it into the query string, either like so:

'{"query": {"bool": {"must": [{"match": { "source": "server_one" }},{"match": {"srcip": {} }}],"filter":[ {"range" : {"timestamp" :{"gte": "now-1d", "lte": "now"}}}]}}}'.format(sourceip)

Or, more elegantly in my opinion:

import json
query = {"query": {"bool": {"must":[
    {"match": { "source": "server_one" }},
    {"match": {"srcip": sourceip }}
],
"filter":[{"range" : {"timestamp" :{"gte": "now-1d", "lte": "now"}}}]
}}
query = json.dumps(query)
omu_negru
  • 4,642
  • 4
  • 27
  • 38