Skip to content

Instantly share code, notes, and snippets.

@jstrassburg
Created July 11, 2015 14:23
Show Gist options
  • Save jstrassburg/2f55e9244f5048c542c2 to your computer and use it in GitHub Desktop.
Save jstrassburg/2f55e9244f5048c542c2 to your computer and use it in GitHub Desktop.
elasticsearch-py spatial example
from datetime import datetime
from elasticsearch import Elasticsearch
class Program():
es = Elasticsearch()
def __init__(self):
pass
@staticmethod
def main():
Program.spatial_test()
@staticmethod
def spatial_test():
index_name = "my-index"
doc_type_name = "my-doc"
mapping = {
doc_type_name: {
"properties": {
"account_email": {"type": "string"},
"expiration_date": {"type": "date", "format": "YYYY-MM-dd"},
"text": {"type": "string"},
"location": {
"type": "geo_point",
"fielddata": {
"format": "compressed",
"precision": "3m" # to save memory, use lossy compression and lower precision
}
}
}
}
}
# The indices.create method isn't idempotent hence the check for existence
if not Program.es.indices.exists(index_name):
Program.es.indices.create(index_name)
Program.es.indices.put_mapping(index=index_name, doc_type=doc_type_name, body=mapping)
doc = {
"account_email": "[email protected]",
"expiration_date": "2015-07-15",
"text": "Hey there. Nice to see you nearby dude!",
"location": {
"lat": 33.892265,
"lon": -118.224154
}
}
# This would be idempotent if I specify the id
# Since I don't this manifests as a POST and a new document would get created each time with
# an autogenerated id, hence the delete in the for loop below
result = Program.es.index(index=index_name, doc_type=doc_type_name, body=doc)
print(result['created'])
Program.es.indices.refresh(index=index_name)
query = {
"query": { "match_all": {}},
"filter": {
"geo_distance": {
"distance": "5km",
"location": {
"lat": 33.895956,
"lon": -118.203982
}
}
}
}
result = Program.es.search(index=index_name, body=query)
print("Got %d hits: " % result['hits']['total'])
for hit in result['hits']['hits']:
print("message from %(account_email)s: %(text)s" % hit["_source"])
Program.es.delete(index=index_name, doc_type=doc_type_name, id=hit['_id'])
if __name__ == "__main__":
Program.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment