Filter on array of object

I have a documents with many nested fields and array of objects inside them. So when I perform search, how can I get only the matching object inside the array of object, not the entire document?

{
  "name": "Olivia",
  "jobs": [
    {
      "title": "Accountant",
      "offices": [
        {
          "city": "Paris",
          "address": "Her adress"
        },
        {
          "city": "NYC",
          "address": "New adress"
        }
      ]
    },
    {
      "title": "Judge",
      "offices": [
        {
          "city": "Paris",
          "address": "Judge adress"
        },
        {
          "city": "NYC",
          "address": "New judge adress"
        }
      ]
    }
  ]
}

Jobs and offices are nested What I want to have in my search are: her name, jobs and offices where the city is "Paris", in normal search I get both of the offices where city are Paris and NYC

Is there a way to get only the offices having "Paris" as city?

Hi @My-project-repositor,

I don't think it's possible, unless you change the way you store your data. The only slightly related thing that's available is Source Filtering.

Best,
Oleg

Thank you, I found the solution
We can use inner hits

{
  "query": {
    "nested": {
      "path": "jobs.offices",
      "query": {
        "bool": {
          "must": [
            {
              "match": {
                "jobs.offices.city": "Paris"
              }
            }
          ]
        }
      },
      "inner_hits": {
        "_source": [
          "jobs.offices.address"
        ]
      }
    }
  }
}

This link also helped stackoverflow.com/a/63133940/4604579

2 Likes

Awesome, thanks for sharing your finding!

2 Likes

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.