# Elasticsearch nested query ordered by “hits”

**URL:** <https://discuss.elastic.co/t/elasticsearch-nested-query-ordered-by-hits/60219>\
**Category:** Elasticsearch\
**Created:** [September 10, 2016, 2:48pm UTC](https://discuss.elastic.co/t/elasticsearch-nested-query-ordered-by-hits/60219 "2016-09-10T14:48:03Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![priedthirdeye](https://avatars.discourse-cdn.com/v4/letter/p/d78d45/32.png) [@priedthirdeye](https://discuss.elastic.co/u/priedthirdeye)\
**Post date:** [September 10, 2016, 2:48pm UTC](https://discuss.elastic.co/t/elasticsearch-nested-query-ordered-by-hits/60219/1 "2016-09-10T14:48:03Z")

</div>

Using Elasticsearch, I'm trying to search nested data and return the documents with the most "hits."

Relevant Example Data

```
POST myrecipes/recipe
{
    "title": "Potato Salad",
	"ingredients": [
		{"name":"potato"},
		{"name":"mayonaise"},
		{"name":"mustard"},
		{"name":"bacon"},
		{"name":"onion"},
		{"name":"parsley"}	
	]
}

POST myrecipes/recipe
{
	"title": "Seared Scallops",
	"ingredients": [
		{"name":"scallops"},
		{"name":"butter"},
		{"name":"bacon"}
	]
}

POST myrecipes/recipe
{
	"title": "Tuna melt",
	"ingredients": [
		{"name":"tuna"},
		{"name":"onion"},
		{"name":"butter"},
		{"name":"bacon"},
		{"name":"mayonaise"},
		{"name":"lettuce"},
		{"name":"tomato"},
		{"name":"bread"}
	]
}

```

My Index

```
PUT myrecipes
{
  "mappings": {
    "recipe": {
      "properties": {
        "ingredients": {
          "type": "nested",
          "include_in_parent": true,
          "properties": {
            "name": {
                "type": "string",
                "fields": {
                    "untouched": {
                        "type": "string",
                        "index": "not_analyzed"
                    }
                }              
            }            
          }
        }
      }
    }
  }
}

```

My Search:

```
POST myrecipes/recipe/_search
{
	"query": {
		"nested": {
		  "path": "ingredients",
		  "query": {
		    "bool": {
		      "should": [
				{
				  "match": {
				    "ingredients.name": {
				      "query": "bacon"
				    }
				  }
				},
				{
				  "match": {
				    "ingredients.name": {
				      "query": "butter"
				    }
				  }
				}
		      ]
		    }
		  }
		}
	}
}

```

The query returns

"Tuna melt", "Potato Salad", "Seared Scallops"

I'm hoping for:

"Seared Scallops", "Tuna melt", "Potato Salad"

Since there are two "hits" on "Seared scallops" and "Tuna Melt" (bacon and butter), and only one "hit" on "Potato Salad" (bacon).

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [July 5, 2017, 10:21pm UTC](https://discuss.elastic.co/t/elasticsearch-nested-query-ordered-by-hits/60219/2 "2017-07-05T22:21:22Z")

</div>


