0
votes

I have inserted some data like below in elastic search. The data (name_list) looks like below.

{
  "manage": {
    "name_list": [
      {
        "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"]
      }
    ]
  }
}

I'm trying to write a elastic search query using elasticsearch_dsl python module Q.

My simple query to get the names matching name_gr regexp -> gr.* looks like below :

{"query":{"regexp":{"name_gr":"gr.*"}}}

Query to get the name which has name_gr as "gr5" looks like:

{"query":{"regexp":{"name_gr":"gr5"}}}

Now, my question is : What should be my query if i want to get all the names which has name_gr as "gr1" and "gr2"?

For eg: Let's say my regexp for name_gr in this case will look like :

{"regexp":{"name_gr":"gr[12]"}}

Now, my result should contain names as name1, name2 and name4 as name also contains both gr1 and gr2.

I don't know how do i form the query in this case, i think it i will contain "must", "match". But no idea on how to form it.

Please help.

PS :

{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "name_gr": "gr1"
          }
        },
        {
          "match": {
            "name_gr": "gr2"
          }
        }
      ]
    }
  }
}

This query works, but my input can be a regexp, for eg: my input can be

gr[12], so my query should look something like this (syntax is wrong, which is to be fixed):

{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "regexp": {
              "name_gr": "gr[12]"
            }
          }
        }
      ]
    }
  }
}  

So, in this query above "match" portion should get internally resolved into ->

"must": [
            {
              "match": {
                "name_gr": "gr1"
              }
            },
            {
              "match": {
                "name_gr": "gr2"
              }
            }
          ]
        }
1
@aclokay can you please check this question? - zubug55

1 Answers

0
votes

I am not sure what's there in your name_gr, I am assuming it has only one value, it may be anything (like: gr1, gr2, gr3...etc).

So in that case where name_gr has gr1 or gr2:

{
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "name_gr": "gr1"
          }
        },
        {
          "match": {
            "name_gr": "gr2"
          }
        }
      ]
    }
  }
}

If name_gr is a list then you query will look like this:

{
  "query": {
    "bool": {
      "must": [
        {
          "regexp":{"name_gr":"gr.*"}
        },
        {
          "regexp":{"name_gr":"gr.*"}
        }
      ]
    }
  }
}