Home > Software design >  Elasticsearch. How to pick 4 matches from each Title?
Elasticsearch. How to pick 4 matches from each Title?

Time:11-19

I wish to pick 4 different recipes from my doc by title.

I tried something like this:

        body: {
      '_source': {
        'includes': 4,
      },
      'size': 4,
      'query': {
        bool: {
          should: [
            {match: {Title: {query: 'Eggs', operator: 'OR'}}},
            {match: {Title: {query: 'Apple', operator: 'OR'}}},
            {match: {Title: {query: 'Onion', operator: 'OR'}}},
            {match: {Title: {query: 'spaghetti', operator: 'OR'}}},
          ],
        },
      },
    }

But without success. It finds only spaghetti recipe but if Im looking for onion recipes I can find them in another query so my merged query makes nosense :(

CodePudding user response:

It is not possible to fetch "n" documents per clause in query part. You need to use top_hits aggregation to achieve it.

{
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "Title": {
              "query": "Eggs",
              "operator": "OR"
            }
          }
        },
        {
          "match": {
            "Title": {
              "query": "Apple",
              "operator": "OR"
            }
          }
        },
        {
          "match": {
            "Title": {
              "query": "Onion",
              "operator": "OR"
            }
          }
        },
        {
          "match": {
            "Title": {
              "query": "spaghetti",
              "operator": "OR"
            }
          }
        }
      ]
    }
  },
  "aggs": {
    "recipies": {
      "terms": {
        "field": "Title.keyword",
        "size": 10000
      },
      "aggs": {
        "docs": {
          "top_hits": {
            "size": 4
          }
        }
      }
    }
  }
}

Terms aggregation will work like group by and top_hits will return top "4" documents for each group.

  • Related