Search code examples
sortingelasticsearchelastic-appsearch

How to make geo Location sorting work in elastic


I'm trying to sort by location. Similar data and tests work correctly in Elasticsearch but fail using Elastic App Search (latest 8.3 version). The results should be in the following order "Item-2, Item-3, Item-1", instead they are in this order "Item-1, Item-2, Item-3".

Request body:

{
  "query": "",
  "sort": {
    "location": {
      "center": [
        0,
        14
      ],
      "order": "asc"
    }
  },
  "page": {
    "size": 10,
    "current": 1
  }
}

Response body

{
  "meta": {
    "alerts": [],
    "warnings": [],
    "precision": 2,
    "engine": {
      "name": "test-core-item",
      "type": "default"
    },
    "page": {
      "current": 1,
      "total_pages": 1,
      "total_results": 6,
      "size": 10
    },
    "request_id": "c8f5aaaa71d9f152f203f5effd995031"
  },
  "results": [
    {
      "location": {
        "raw": "0.0,0.0"
      },
      "_meta": {
        "id": "Item-1",
        "engine": "test-core-item",
        "score": null
      },
      "id": {
        "raw": "Item-1"
      }
    },
    {
      "location": {
        "raw": "0.0,10.0"
      },
      "_meta": {
        "id": "Item-2",
        "engine": "test-core-item",
        "score": null
      },
      "id": {
        "raw": "Item-2"
      }
    },
    {
      "location": {
        "raw": "0.0,20.0"
      },
      "_meta": {
        "id": "Item-3",
        "engine": "test-core-item",
        "score": null
      },
      "id": {
        "raw": "Item-3"
      }
    }
  ]
}

Solution

  • According to the docs Geolocation raw data can be repsesented in different ways, e.g. as a string of ", " or as an array with elements [, ] (see docs). Notice that when passing as string latitude is passed first but when passing as an array longitude is first.

    Please mind the difference in the order of coordinates and either pass

    "center": [14, 0] or "center": "0, 14"

    So in the example above, the center should have been passed as [14, 0] instead of [0, 14].