0

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.

1 Answer 1

2

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'
                          }
                        }]
                     }
                   }
                }
              }
            ]
        }
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

would I need to update my mapping to get the desired result?
It worked. Thanks mate!! Answer is accepted but SO is stopping me right now! So will do it when allowed to.
No your mapping is fine, just the query was malformed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.