Quick Start¶
First of all create Elasticsearch cluster and index objects:
from elasticsearch import Elasticsearch
from elasticmagic import Cluster, Index
es_cluster = Cluster(Elasticsearch())
es_index = Index(es_cluster, 'test')
Let’s describe elasticsearch document:
from elasticmagic import Document, Field
from elasticmagic.types import String, Integer, Float
class ProductDocument(Document):
__doc_type__ = 'product'
name = Field(String, fields={
'sort': Field(
String, index='no', doc_values=True, analyzer='keyword'
),
})
status = Field(Integer)
price = Field(Float)
To create or update document mapping just run:
es_index.put_mapping(ProductDocument)
Try to reindex some documents:
from decimal import Decimal
doc1 = ProductDocument(
name="Lego Ninjago Cole's dragon",
status=0,
price=Decimal('10.99'),
)
doc2 = ProductDocument()
doc2.name = 'Lego minifigure'
doc2.status = 1
doc2.price = Decimal('2.50')
result = es_index.add([doc1, doc2])
assert result.errors == False
Now we can build query:
search_query = (
es_index.search_query(ProductDocument.name.match('lego'))
.filter(ProductDocument.status == 0)
.order_by(ProductDocument.name.sort)
.limit(20)
)
And finally make request and process result:
for doc in search_query:
print('{}: {}'.format(doc._id, doc.name))
Let’s build a histogram by price:
from elasticmagic import agg
search_query = (
es_index.search_query()
.filter(ProductDocument.status == 0)
.aggs({
'prices': agg.Histogram(ProductDocument.price, interval=20)
})
.limit(0)
)
for bucket in search_query.result.get_aggregation('prices').buckets:
print('{} ({})'.format(bucket.key, bucket.doc_count))