cynical biscuit
cynical biscuit

Reputation: 353

Elasticsearch Python client to add geo_point

I'm using Elasticsearch 2.2.0; however, I'm really struggling trying to add geo_point data. In fact, the the geocoded data get's added as a string.

Expected: "geo":{"properties":{"location":{"type":"geo_point"}}}

Actual: "geo":{"properties":{"location":{"type":"string"}}}

I'm adding the data in python the following way:

from elasticsearch import Elasticsearch
es = Elasticsearch()

# ... 
es_entries['geo'] = { 'location': str(data['_longitude_'])+","+str(data['_latitude_'])}
# ...

es.index(index="geodata", doc_type="doc", body=es_entries)

Is there any tutorial on adding geo_point data through python (this is not as simple as it may seem)?

Upvotes: 2

Views: 7912

Answers (2)

Val
Val

Reputation: 217344

You need to specify the geo_point type in the mapping while creating your index with es.indices.create().

That call takes a body argument containing the settings and mappings of your index.

mappings = {
    "doc": {
        "properties": {
            "geo": {
                 "properties": {
                     "location": {
                         "type": "geo_point"
                     }
                 }
             }
        }
    }
}
es.indices.create(index='geodata', body=mappings)

# ... 
es_entries['geo'] = { 'location': str(data['_longitude_'])+","+str(data['_latitude_'])}
# ...
es.index(index="geodata", doc_type="doc", body=es_entries)

UPDATE ES7

In ES7, document types are not necessary anymore, so the solution changes to this (no more doc):

mappings = {
    "properties": {
        "geo": {
             "properties": {
                 "location": {
                     "type": "geo_point"
                 }
             }
         }
    }
}

Upvotes: 7

Carlos Vega
Carlos Vega

Reputation: 1371

With elasticsearch-dsl you should do like:

Class MyDoc(DocType):
    geo = GeoPoint()

# Geo-point expressed as an object, with lat and lon keys.
doc = MyDoc(geo={'lat': 52.5720661, 'lon': 52.5720661})
#or Geo-point expressed as a string with the format: "lat,lon".
doc = MyDoc(geo='52.5720661, 52.5720661')
# or Geo-point expressed as an array with the format: [ lon, lat]
doc = MyDoc(geo=[52.5720661,52.5720661])

I wouldn't use multiple formats but keep the same.

References:

https://www.elastic.co/guide/en/elasticsearch/reference/current/geo-point.html https://github.com/elastic/elasticsearch-dsl-py/issues/398

Upvotes: 0

Related Questions