Skip to content

Instantly share code, notes, and snippets.

@geekpete
Created January 31, 2017 10:44
Show Gist options
  • Save geekpete/74f3e8b5fa68893bda6dab01575e86a6 to your computer and use it in GitHub Desktop.
Save geekpete/74f3e8b5fa68893bda6dab01575e86a6 to your computer and use it in GitHub Desktop.
Counting all docs in an Elasticsearch nested mapping index
# ensure the test index is deleted if we've tested previously
DELETE /my_index/
# create the index with two nested fields
PUT my_index
{
"mappings": {
"my_type": {
"properties": {
"user": {
"type": "nested"
},
"contact_details": {
"type": "nested"
}
}
}
}
}
# Run this post several times to create a few docs
POST my_index/my_type/
{
"some test field": "testing 123",
"another test field": "some regular field string",
"user": [
{
"first": "John",
"last": "Smith"
},
{
"first": "Alice",
"last": "White"
}
],
"contact_details": [
{
"Name": "John Smith",
"Phome": "555-935-901"
},
{
"Name": "Alice White",
"Email": "alice.white@somemail.yurgle"
}
]
}
# take a look at the docs we've created
GET /my_index/_search
# Now run a match_all query with an agg per nested field
# The total docs in the index is the sum of the hits and the aggregations.
GET /my_index/_search
{
"query" : {
"match_all": {}
},
"size": 0,
"aggs" : {
"user" : {
"nested" : {
"path" : "user"
}
},
"contact_details": {
"nested": {
"path": "contact_details"
}
}
}
}
# count only counts the parent docs of a nested mapping
GET /my_index/_count
# the cat api counts all the docs including the nested docs as separate docs in the count.
# Verify your nested aggregation sum count is the same as the cat api docs count.
GET /_cat/indices/my_index?v
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment