简体   繁体   中英

Elastic search query find exact match of values in the list from regexp input parameter

My data looks like below:

  {
    "name": "name1",
    "name_gr": ["gr1","gr2"]
  },
  {
    "name": "name2",
    "name_gr": ["gr1","gr2"]
  },
  {
    "name": "name3",
    "name_gr": ["gr2","gr3"]
  },
  {
    "name": "name4",
    "name_gr": ["gr1","gr2","gr3","gr4"]
  },
  {
    "name": "name4",
    "name_gr": ["gr4","gr5"]
  }

Now, i am trying to write elastic search query using elasticsearch_dsl python module by importing Q from it.

My input query will be some regex on "name_gr" . For eg: "name_gr": "gr[12]" . So, in this case I want all the names which has both "gr1" and "gr2" in their list of "name_gr".

So, the result for ->

Example 1 : "name_gr": "gr[12]" will be :

  {
    "name": "name1",
    "name_gr": ["gr1","gr2"]
  },
  {
    "name": "name2",
    "name_gr": ["gr1","gr2"]
  },
  {
    "name": "name4",
    "name_gr": ["gr1","gr2","gr3","gr4"]
  }

because, gr1 and gr2 both are present in name1, name2 and name4.

Example 2: "name_gr": "gr.*" will be :

  {
    "name": "name4",
    "name_gr": ["gr1","gr2","gr3","gr4"]
  }

because, all the gr's (gr1,gr2,gr3,gr4) are present in name4 only.

I tried writing my query like below:

must = [{'match':{'regexp': {'name_gr': 'gr[12]'}}}]
result = Q('bool', must = must)

But it gives name3 also in result, which is invalid as both gr1 and gr2 are not present in it. Please help. I am stuck in this from few days now.

Thanks.

You are using a match query in your example where you want to be using regexp instead. To do this just use:

s = Search().query('regexp', name_gr='gr[12]')
s.execute()

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM