How to get item highest matching rate in nested data!

Hi, I have an index with nested data.

[
  {
    "shop": {
      "name": "The shop",
      "products": [
        {
          "name": "the product 1",
          "price": 1000
        },
        {
          "name": "product 2",
          "price": 1000
        }
      ]
    }
  },
  {
    "shop": {
      "name": "The shop 2",
      "products": [
        {
          "name": "shop 2 product 1",
          "price": 1000
        },
        {
          "name": "shop 2 product 2",
          "price": 1000
        }
      ]
    }
  }
]

I query nested data with this query:

{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "products",
            "query": {
              "multi_match": {
                "query": "the product",
                "fields": [
                  "products.name"
                ]
              }
            }
          }
        }
      ]
    }
  }
}

And get a response like that

{
  "hits": [
    {
      "_index": "shops",
      "_score": 223.1123,
      "_source": {
        "name": "The shop",
        "products": [
          {
            "name": "the product 1",
            "price": 1000
          },
          {
            "name": "product 2",
            "price": 1000
          }
        ]
      }
    },
    {
      "_index": "shops",
      "_score": 203.1123,
      "_source": {
        "name": "The shop 2",
        "products": [
          {
            "name": "shop 2 product 1",
            "price": 1000
          },
          {
            "name": "shop 2 product 2",
            "price": 1000
          }
        ]
      }
    }
  ]
}

Currently, I don't the product 1 and product 2 which one has a higher score.
It's possible in elasticseach to response percent matching for each field or something like that.
Thank you!

Yes, you can add inner_hits to your nested query. This will by default return you the top three best matching nested objects and their scores:

{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "products",
            "query": {
              "multi_match": {
                "query": "the product",
                "fields": [
                  "products.name"
                ]
              }
            },
            "inner_hits": {
            }
          }
        }
      ]
    }
  }
}

Btw, that bool query with just a single must clause does not do anything. The following query will return the exact same results:

{
  "query": {
    "nested": {
      "path": "products",
      "query": {
        "multi_match": {
          "query": "the product",
          "fields": [
            "products.name"
          ]
        }
      },
      "inner_hits": {}
    }
  }
}
1 Like

Thank you so much :drooling_face:

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