Skip to content

Instantly share code, notes, and snippets.

@pcdinh
Forked from markbirbeck/gist:1433393
Created January 2, 2012 15:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pcdinh/1551176 to your computer and use it in GitHub Desktop.
Save pcdinh/1551176 to your computer and use it in GitHub Desktop.
[ElasticSearch] Using facets when querying parent/child documents
# Create an index:
#
curl -XDELETE 'http://127.0.0.1:9200/articles'
curl -XPUT 'http://127.0.0.1:9200/articles'
# Insert the action mapping, as a child of articles:
#
curl -XPUT 'http://127.0.0.1:9200/articles/action/_mapping' -d '
{
"action": {
"_parent": {
"type": "article"
},
"properties": {
"action": {
"store": true,
"type" : "string"
},
"date": {
"store": true,
"type" : "date"
}
}
}
}
'
# Insert some articles:
#
curl -XPUT 'http://127.0.0.1:9200/articles/article/1' -d '{"title": "One"}'
curl -XPUT 'http://127.0.0.1:9200/articles/article/2' -d '{"title": "Two"}'
# Insert some actions that happened to those articles:
#
curl -XPOST 'http://127.0.0.1:9200/articles/action?parent=1' -d '{"date": "2011-11-18", "action": "created"}'
curl -XPOST 'http://127.0.0.1:9200/articles/action?parent=2' -d '{"date": "2011-11-18", "action": "created"}'
curl -XPOST 'http://127.0.0.1:9200/articles/action?parent=2' -d '{"date": "2011-11-23", "action": "published"}'
# Ensure the index is up-to-date:
#
curl -XPOST 'http://127.0.0.1:9200/articles/_refresh'
# Now search for all articles that contain 'One' in the title, and have actions that took place
# between 15th and 30th of November. Create facets for those actions:
#
curl -XGET 'http://127.0.0.1:9200/articles/_search' -d '
{
"query": {
"bool": {
"must": [
{
"text": {
"title": {
"query": "One",
"type": "boolean"
}
}
},
{
"has_child": {
"query": {
"range": {
"date": {
"to": "2011-11-30",
"from": "2011-11-15"
}
}
},
"type": "action",
"_scope": "actions"
}
}
]
}
},
"facets": {
"created_facet": {
"date_histogram": {
"interval": "day",
"params": {
"param1": "created"
},
"key_field": "date",
"value_script": "doc[\"action\"].value == param1 ? 1 : 0"
},
"scope": "actions"
},
"published_facet": {
"date_histogram": {
"interval": "day",
"params": {
"param1": "published"
},
"key_field": "date",
"value_script": "doc[\"action\"].value == param1 ? 1 : 0"
},
"scope": "actions"
}
},
"from": 0,
"size": 10
}
'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment