4

I'm pretty new to programing so my question might be stupid/easy to do but: i need to create multiple filters in elasticsearch based on user input

my body of query:

body = {
        "query": {
            "filtered": {
                "filter": {
                    "bool": {
                        "must": [
                            {"term": {name1: value1}},
                            {"term": {name2: value2}},
                            {"term": {name3: value3}},
                        ]
                    }
                }
            }
        },
}

And it works fine but i need to have dynamic number of these filters

I tried to build query into string and then add filters inside but es dont allow it eg:

l = []
for i_type, name in convert.items():
    string = '{"term": {"' + i_type + '":"' + name + '"}},'
    l.append(string)
i_query = ''.join(l)

when i use list/string in query structure im getting 404 errors from server

Is it even possible to add dynamic number of filters?

Derpos
  • 41
  • 2

1 Answers1

5

It is possible. The body is just a Python dictionary. So you can add dynamically your fields/terms/new filters and so on.

    body = {
    "query": {
        "filtered": {
            "filter": {
                "bool": {
                    "must": []
                    }
                }
            }
        }
   }

d = {"name_1": value_1, "name_2": value_2}

Python 2.x

for key, value in d.iteritems():
    body1["query"]["filtered"]["filter"]["bool"]["must"].append({"term": {key: value}})

Or shorter (Python 2.x):

body1["query"]["filtered"]["filter"]["bool"]["must"].extend([{"term": {key: value}} for key,value in d.iteritems()])

Python 3.x

for key, value in d.items():
    body1["query"]["filtered"]["filter"]["bool"]["must"].append({"term": {key: value}})  

The shorter version for Python 3.x:

body1["query"]["filtered"]["filter"]["bool"]["must"].extend([{"term": {key: value}} for key,value in d.items()])

Basically, you can create whatever query you want. For example, you can easily add the should clause:

body["query"]["filtered"]["filter"]["bool"]["should"]=[{"term": {"name_42": value_42}}]
Andrey Moerov
  • 51
  • 1
  • 2