Search code examples
elasticsearchgeolocationelastic-stack

How to save geo data in elasticsearch


How do I index a document with below data in elasticsearch(geo datatype)?

<west>5.8663152683722</west>
<north>55.0583836008072</north>
<east>15.0418156516163</east>
<south>47.2701236047002</south>

I tried geo_point and its working for lon and lat's, not sure how to save this data. any help is highly appreciated.


Solution

  • You'll have to use the geo_shape datatype and convert your XML (I assume) semi-points into a line string or polygon before sync.


    I'm gonna go with a polygon here. Let's visualise the conventional cardinal directions:

                 North (+90)
                   |
    (-180) West  ——+—— East (+180)
                   |
                 South (-90)
    

    geo_shape expects GeoJSON-like inputs so you'll need five coordinate points, the first and last of which are identical (according to the GeoJSON spec).

    Therefore, borrowing from TurfJS and going from bottom left counter-clockwise,

    const lowLeft = [west, south];
    const topLeft = [west, north];
    const topRight = [east, north];
    const lowRight = [east, south];
    
    return 
    [ 
      [
        lowLeft,
        lowRight,
        topRight,
        topLeft,
        lowLeft
      ]
    ]
    

    Finally, let's create our index and plug your numbers in

    PUT /example
    {
      "mappings": {
        "properties": {
          "location": {
            "type": "geo_shape"
          }
        }
      }
    }
    
    POST /example/_doc
    {
      "location":{
        "type":"polygon",
        "coordinates":[
          [
            [
              5.8663152683722,
              47.2701236047002
            ],
            [
              15.0418156516163,
              47.2701236047002
            ],
            [
              15.0418156516163,
              55.0583836008072
            ],
            [
              5.8663152683722,
              55.0583836008072
            ],
            [
              5.8663152683722,
              47.2701236047002
            ]
          ]
        ]
      }
    }
    

    Then verify that the center of your square if indeed inside of your indexed polygon:

    GET example/_search
    {
      "query": {
        "geo_shape": {
          "location": {
            "shape": {
              "type": "point",
              "coordinates": [
                10.45406545999425,
                51.1642536027537
              ]
            },
            "relation": "intersects"
          }
        }
      }
    }