Search code examples
elasticsearchnestedelastic-stack

Elastic search exclude a nested element from search results, get element by id


I have item with nested objects:

          {
                "name": "The Amazon rainforest",
                "id": "610d33da26c25b00191ebcbe",
                "tags": [
                    {
                        "name": "Brazil",
                        "verified": 1
                    },
                    {

                        "name": "new_tag",
                        "verified": 0,
                    }
                ],

            }

in search results unverified tag should be omitted:

output of search by id: 610d33da26c25b00191ebcbe

          {
                "name": "The Amazon rainforest",
                "id": "610d33da26c25b00191ebcbe",
                "tags": [
                    {
                        "name": "Brazil",
                        "verified": 1
                    }
                ],

            }

Solution

  • Node.js version of answer:

          const { body } = await elasticWrapper.client.search({
            index: ElasticIndexs.Products,
            filter_path:
              'hits.hits._source*, hits.hits.inner_hits.tags.hits.hits._source*',
            body: {
              _source: {
                excludes: ['tags'],
              },
              query: {
                bool: {
                  must: [
                    {
                      match: {
                        id: req.params.id,
                      },
                    },
                  ],
                  should: [
                    {
                      nested: {
                        path: 'tags',
                        query: {
                          term: {
                            'tags.verified': 1,
                          },
                        },
                        inner_hits: {},
                      },
                    },
                  ],
                },
              },
            },
          });