Has_child data retrival

I have a few types like so:

First the mapping:

curl -XPUT localhost:9200/test/account/_mapping -d '{
"name": {
"type": "string"
}
}'

curl -XPUT 'http://localhost:9200/test/email/_mapping' -d '{

"email" : {
    "_parent" : {"type" : "account"}
}

}'

Some data:

curl -XPUT http://localhost:9200/test/account/1 -d '{
"name": "Andy Boyce",
}'

curl -XPUT http://localhost:9200/test/account/2 -d '{
"name": "Catherine Davids",
}'

curl -XPUT http://localhost:9200/test/account/3 -d '{
"name": "Elizabeth Faraday",
}'

curl -XPUT http://localhost:9200/test/email/1?parent=1 -d '{
"email": "andy@boyce.com"
}'

curl -XPUT http://localhost:9200/test/email/2?parent=1 -d '{

"email": "andy.boyce@company.com"

}'

curl -XPUT http://localhost:9200/test/email/3?parent=1 -d '{

"email": "support@corporation.com"

}'

curl -XPUT http://localhost:9200/test/email/4?parent=2 -d '{

"email": "cat@designgroup.com"

}'

curl -XPUT http://localhost:9200/test/email/5?parent=3 -d '{
"email": "ef@company.com"
}'

curl -XPUT http://localhost:9200/test/email/6?parent=3 -d '{
"email": "liz@personalblog.com"
}'

I am then running a simple query to search onemail.email and
account.name. Essentially, if we get a match on email.email, only the
parent account will be present in the results:

curl 'http://localhost:9200/test/account/_search' -d '{
"query": {
"bool": {
"should": [
{
"prefix": {
"name": "a"
}
},
{
"has_child": {
"type": "email",
"query": {
"prefix": {
"email": "a"
}
}
}
}
],
"minimum_number_should_match" : 1
}
}
}'

This works fine, but the problem is that once I get the accounts, I need to
know if the match was on email.email or account.name. For example, I
would like to display an email address in the results for each account. If
the match was on the email address, then I would like to display the
matched email address. If the match was on the account name, I would like
to display the first email address ('lowest id') linked to the account.

How can this be done?

Including the top email address (email with lowest id) per account
isn't possible in one search request.
What you could do is executing subsequent search requests. For each
account returned
in the search result, you'll need to execute a search request.

Or you could change your mapping, so that each account has an email
address field.

Martijn

Hi Martin,

Multiple emails can be associated to one account.

Would changing the mapping so that accounts contain emails help deal with
the issue? Please forgive my ignorance as I am quite new to ES :slight_smile:

I think it would. You can associate multiple email addresses with one account:

To find out what email addresses have matched with your query you can
use highlighting on the email field:

Martijn