Skip to content

Commit

Permalink
Sort results by distance to the point
Browse files Browse the repository at this point in the history
  • Loading branch information
liowalter committed Sep 7, 2024
1 parent dc9618a commit 5efdfd2
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 7 deletions.
40 changes: 34 additions & 6 deletions api/app/elastic.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,46 @@ def search_documents(self, longitude: float, latitude: float, radius: str) -> li
"""Search for documents in the index, returning only a list of documents as dicts"""
response = self.search(
{
"bool": {
"must": {"match_all": {}},
"filter": {"geo_distance": {"distance": radius, "coordinates": {"lon": longitude, "lat": latitude}}},
}
},
"size": 1000,
"query": {
"bool": {
"must": {
"match_all": {}
},
"filter": {
"geo_distance": {
"distance": radius,
"coordinates": {
"lat": latitude,
"lon": longitude
}
}
}
}
},
"sort": [
{
"_geo_distance": {
"coordinates": {
"lat": latitude,
"lon": longitude
},
"order": "asc",
"unit": "km",
"mode": "min",
"distance_type": "arc",
"ignore_unmapped": True
}
}
]
}
)
hits = response["hits"]["hits"]
return list(map(itemgetter("_source"), hits))

def search(self, query: dict) -> ObjectApiResponse:
"""Search for documents in the index, returning the elastic search response."""
return self.connection.search(index=self.index_name, query=query, size=1000)
return self.connection.search(index=self.index_name, body=query)

def index(self, document: dict) -> None:
"""Add a document to the elasticsearch index."""
Expand Down
2 changes: 1 addition & 1 deletion api/tests/test_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def test_photos_querying(self):
},
)
self.assertEqual(response.status_code, 200)
self.assert_json_equal([rathausquai, seeblick], response.json())
self.assert_json_equal([seeblick, rathausquai], response.json())

response = self.client.get(
"/api/photos",
Expand Down

0 comments on commit 5efdfd2

Please sign in to comment.