Rajesh Yogeshwar Rajesh Yogeshwar - 22 days ago 6
Python Question

Elasticsearch querying nested objects returning no results

I have created Elasticsearch index and one of the nested field has mapping as following.

"groups": {
"type": "nested",
"properties": {
"name": {
"type": "text"
},
"value": {
"type": "text"
}
}
}


On details about ES version, its 5.0 and I am using official python client elasticsearch-py on client side. I want to query this nested field based on its value.

Lets say there is another field called name which is a text type field. I want to find all name starting with A and falling under group specified.

Some sample data,

Groups - HR(name=HR, value=hr), Marketing(name=Marketing, value=marketing)
Names - Andrew, Alpha, Barry, John

Andrew and Alpha belong to group HR.

Based on this I tried a query

{
'query': {
'bool': {
'must': [{
'match_phrase_prefix': {
'title': 'A'
}
}]
},
'nested': {
'path': 'groups',
'query': {
'bool': {
'must': [{
'match': {
'groups.value': 'hr'
}
}]
}
}
}
}
}


For this query I referred ES docs but this query does not return anything. It would be great if someone can point out what is wrong with this query or mapping itself.

Val Val
Answer

You're almost there, you simply need to move the nested query inside the bool/must query:

{
    'query': {
        'bool': {
            'must': [
              {
                'match_phrase_prefix': {
                    'title': 'A'
                }
              },
              {
                'nested': {
                   'path': 'groups',
                   'query': {
                     'bool': {
                       'must': [{
                          'match': {
                            'groups.value': 'hr'
                          }
                        }]
                     }
                   }
                }
              }
            ]
        }
    }
}