Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save karmi/792228 to your computer and use it in GitHub Desktop.
Save karmi/792228 to your computer and use it in GitHub Desktop.
Searching and facets in ElasticSearch
# (Re)create the index
#
curl -X DELETE "http://localhost:9200/articles"
curl -X PUT "http://localhost:9200/articles"
# Insert the data
#
curl -X POST "http://localhost:9200/articles/article" -d '{ "name" : "One", "tags" : ["ruby"] }'
curl -X POST "http://localhost:9200/articles/article" -d '{ "name" : "Two", "tags" : ["ruby", "python"] }'
curl -X POST "http://localhost:9200/articles/article" -d '{ "name" : "Three", "tags" : ["java"] }'
curl -X POST "http://localhost:9200/articles/_refresh"
# Simple queries
#
curl -X GET "http://localhost:9200/articles/_search?pretty=true&q=tags:ruby"
curl -X GET "http://localhost:9200/articles/_search?pretty=true&q=tags:python"
curl -X GET "http://localhost:9200/articles/_search?pretty=true&q=tags:ruby,python"
# Search for tags "ruby" and "python"
#
curl -X POST "http://localhost:9200/articles/_search?pretty=true" -d '
{
"query" : {
"terms" : {
"tags" : [ "ruby" ]
}
}
}'
# Search for tags "ruby" and "python", results could include just on of the terms
# [!] Notice how it affects the score
#
curl -X POST "http://localhost:9200/articles/_search?pretty=true" -d '
{
"query" : {
"terms" : {
"tags" : [ "ruby", "python" ],
"minimum_match" : 1
}
}
}'
# Search for tags "ruby" and "python", results must include both terms
#
curl -X POST "http://localhost:9200/articles/_search?pretty=true" -d '
{
"query" : {
"terms" : {
"tags" : [ "ruby", "python" ],
"minimum_match" : 2
}
}
}'
# Faceted search on tags (with "match all" query)
#
curl -X POST "http://localhost:9200/articles/_search?pretty=true" -d '
{
"query" : {
"match_all" : {}
},
"facets" : {
"tags" : {
"terms" : {
"field" : "tags",
"size" : 10
}
}
}
}'
# Faceted search on tags (search for "T*" in titles, but exclude "java" in tags)
# [!] Notice that "java" is _excluded_ in facet counts
#
curl -X POST "http://localhost:9200/articles/_search?pretty=true" -d '
{
"query" : {
"query_string" : { "query" : "+name:T* -tags:java"}
},
"facets" : {
"tags" : {
"terms" : {
"field" : "tags",
"size" : 10
}
}
}
}'
# Faceted search on tags (search for "T*" in titles), filtered for tags containing "ruby"
# [!] Notice that "java" is _included_ in facet counts
#
curl -X POST "http://localhost:9200/articles/_search?pretty=true" -d '
{
"query" : {
"query_string" : { "query" : "T*"}
},
"filter" : {
"terms" : { "tags" : ["ruby"] }
},
"facets" : {
"tags" : {
"terms" : {
"field" : "tags",
"size" : 10
}
}
}
}'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment