Skip to content

Instantly share code, notes, and snippets.

@robhudson
Created October 14, 2013 22:27
Show Gist options
  • Select an option

  • Save robhudson/6983314 to your computer and use it in GitHub Desktop.

Select an option

Save robhudson/6983314 to your computer and use it in GitHub Desktop.
An example of doing a "Top 10" query in elasticsearch using a term_stats facet.
import datetime
import random
from collections import defaultdict
from elasticsearch import Elasticsearch
INDEX = 'test-top-books'
TYPE = 'book-sales'
today = datetime.date.today()
books = defaultdict(int)
es = Elasticsearch()
if es.indices.exists(INDEX):
es.indices.delete(INDEX)
# Create index.
es.indices.create(INDEX, {
'settings': {
'index': {
'number_of_replicas': 0
}
}
})
# Populate some test data.
for i in range(1, 31): # 30 days back
for j in range(1, 11): # 10 books
sales = random.randint(1, 100)
books[j] += sales
body = {
'book_id': j,
'date': today - datetime.timedelta(days=i),
'sales': sales,
}
es.index(INDEX, TYPE, body=body)
print 'Top 10 books:'
for id in sorted(books, key=lambda i: books[i], reverse=True):
print 'Book ID:%d, Sales:%d' % (id, books[id])
# Refresh index.
es.indices.refresh(INDEX)
# Perform facet search.
res = es.search(INDEX, body={
'query' : {
'match_all': {}
},
'facets': {
'top_books': {
'terms_stats': {
'key_field': 'book_id',
'value_field': 'sales',
'order': 'total'
}
}
},
'size': 0
})
print
print 'Top 10 according to Elasticsearch:'
for obj in res['facets']['top_books']['terms']:
print 'Book ID:%d, Sales:%d' % (obj['term'], obj['total'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment