Search code examples
elasticsearchelasticsearch-dslelasticsearch-dsl-py

elasticsearch dsl python : how to search by value inside array


I have the following structure in my index:

[
    {
         name:"project1",
         users: [
                   {"id":"1"},
                   {"id":"2"}
         ]
    },
    #... more projects
]

I would like to know how can I get all projects of a specific user (by his id), here is what I have tried :

q = Q("term", id="1") 
resp = projects_index.query("nested",path="users",query=q).execute()

but I get no result, what am I missing ?
Thank you
Edit : here is my index mapping :

   {
      "projects": {
        "mappings": {
          "doc": {
            "properties": {
              "created_at": {
                "type": "date"
              },
              "name": {
                "type": "text"
              },
              "users": {
                "type": "nested",
                "properties": {
                  "id": {
                    "type": "text"
                  }
                }
              }
            }
          }
        }
      }
    }

Solution

  • The reason you are not getting results is because while specifying a nested path you should provide the full name including parent field name i.e. you should use users.id instead of just id. The query thus will translate to as below:

    {
      "query": {
        "bool": {
          "filter": [
            {
              "nested": {
                "path": "users",
                "query": {
                  "term": {
                    "users.id": "1"
                  }
                }
              }
            }
          ]
        }
      }
    }
    

    Suggestion: Change the type of id field to keyword, to prevent id value getting tokenism into multiple terms.