Skip to content

Open Source alternative to Algolia + Pinecone and an Easier-to-Use alternative to ElasticSearch ⚡ 🔍 ✨ Fast, typo tolerant, in-memory fuzzy Search Engine for building delightful search experiences

Geo polygon filtering.

kishorenc33f705caceea
diff --git a/include/field.h b/include/field.h
index 5adf017c..351e8aea 100644
--- a/include/field.h
+++ b/include/field.h
@@ -32,6 +32,7 @@ namespace fields {
static const std::string type = "type";
static const std::string facet = "facet";
static const std::string optional = "optional";
+ static const std::string geo_resolution = "geo_resolution";
}
static const uint8_t DEFAULT_GEO_RESOLUTION = 7;
@@ -198,6 +199,10 @@ struct field {
field_val[fields::type] = field.type;
field_val[fields::facet] = field.facet;
field_val[fields::optional] = field.optional;
+ if(field.is_geopoint()) {
+ field_val[fields::geo_resolution] = field.geo_resolution;
+ }
+
fields_json.push_back(field_val);
if(!field.has_valid_type()) {
@@ -255,6 +260,19 @@ struct field {
field_json[fields::name].get<std::string>() + std::string("` should be a boolean."));
}
+ if(field_json.count(fields::geo_resolution) != 0) {
+ if(!field_json.at(fields::geo_resolution).is_number_integer()) {
+ return Option<bool>(400, std::string("The `geo_resolution` property of the field `") +
+ field_json[fields::name].get<std::string>() + std::string("` should be an integer."));
+ }
+
+ int field_geo_res = field_json.at(fields::geo_resolution).get<int>();
+ if(field_geo_res < 0 || field_geo_res > 15) {
+ return Option<bool>(400, std::string("The `geo_resolution` property of the field `") +
+ field_json[fields::name].get<std::string>() + std::string("` should be between 0 and 15."));
+ }
+ }
+
if(field_json["name"] == "*") {
if(field_json.count("facet") == 0) {
field_json["facet"] = false;
diff --git a/include/index.h b/include/index.h
index 51c41b26..a97d47d7 100644
--- a/include/index.h
+++ b/include/index.h
@@ -15,6 +15,7 @@
#include <field.h>
#include <option.h>
#include <set>
+#include <h3api.h>
#include "string_utils.h"
#include "num_tree.h"
#include "magic_enum.hpp"
@@ -385,6 +386,12 @@ public:
const size_t result_index,
std::unordered_map<size_t, std::vector<std::vector<uint16_t>>> &array_token_positions);
+ static bool is_point_in_polygon(const Geofence& poly, const GeoCoord& point);
+
+ static double transform_for_180th_meridian(Geofence& poly);
+
+ static void transform_for_180th_meridian(GeoCoord& point, double offset);
+
// the following methods are not synchronized because their parent calls are synchronized
art_leaf* get_token_leaf(const std::string & field_name, const unsigned char* token, uint32_t token_len);
diff --git a/include/num_tree.h b/include/num_tree.h
index c5e25414..7b0449c6 100644
--- a/include/num_tree.h
+++ b/include/num_tree.h
@@ -51,6 +51,22 @@ public:
*ids = out;
}
+ size_t get(int64_t value, std::vector<uint32_t>& geo_result_ids) {
+ const auto& it = int64map.find(value);
+ if(it == int64map.end()) {
+ return 0;
+ }
+
+ uint32_t* ids = it->second->uncompress();
+ for(size_t i = 0; i < it->second->getLength(); i++) {
+ geo_result_ids.push_back(ids[i]);
+ }
+
+ delete [] ids;
+
+ return it->second->getLength();
+ }
+
void search(NUM_COMPARATOR comparator, int64_t value, uint32_t** ids, size_t& ids_len) {
if(int64map.empty()) {
return ;
diff --git a/src/collection.cpp b/src/collection.cpp
index 82570652..1acb0a45 100644
--- a/src/collection.cpp
+++ b/src/collection.cpp
@@ -154,6 +154,11 @@ nlohmann::json Collection::get_summary_json() const {
field_json[fields::type] = coll_field.type;
field_json[fields::facet] = coll_field.facet;
field_json[fields::optional] = coll_field.optional;
+
+ if(coll_field.is_geopoint()) {
+ field_json[fields::geo_resolution] = size_t(coll_field.geo_resolution);
+ }
+
fields_arr.push_back(field_json);
}
@@ -1794,31 +1799,50 @@ Option<bool> Collection::parse_geopoint_filter_value(std::string& raw_value,
}
std::vector<std::string> filter_values;
- StringUtils::split(raw_value.substr(1, raw_value.size() - 2), filter_values, ",");
-
- // we will end up with: "10.45 34.56 2 km"
+ auto raw_val_without_paran = raw_value.substr(1, raw_value.size() - 2);
+ StringUtils::split(raw_val_without_paran, filter_values, ",");
- if(filter_values.size() != 3) {
- return Option<bool>(400, format_err_msg);
- }
+ // we will end up with: "10.45 34.56 2 km" or a geo polygon
- if(!StringUtils::is_float(filter_values[0]) || !StringUtils::is_float(filter_values[1])) {
+ if(filter_values.size() < 3) {
return Option<bool>(400, format_err_msg);
}
- std::vector<std::string> dist_values;
- StringUtils::split(filter_values[2], dist_values, " ");
+ // do validation: format should match either a point + radius or polygon
- if(dist_values.size() != 2) {
- return Option<bool>(400, format_err_msg);
+ size_t num_floats = 0;
+ for(const auto& fvalue: filter_values) {
+ if(StringUtils::is_float(fvalue)) {
+ num_floats++;
+ }
}
- if(dist_values[1] != "km" && dist_values[1] != "mi") {
- return Option<bool>(400, "Unit must be either `km` or `mi`.");
+ bool is_polygon = (num_floats == filter_values.size());
+ if(!is_polygon) {
+ // we have to ensure that this is a point + radius match
+ if(!StringUtils::is_float(filter_values[0]) || !StringUtils::is_float(filter_values[1])) {
+ return Option<bool>(400, format_err_msg);
+ }
}
- processed_filter_val = filter_values[0] + " " + filter_values[1] + " " + // co-ords
- dist_values[0] + " " + dist_values[1]; // X km
+ if(is_polygon) {
+ processed_filter_val = raw_val_without_paran;
+ } else {
+ // point + radius
+ std::vector<std::string> dist_values;
+ StringUtils::split(filter_values[2], dist_values, " ");
+
+ if(dist_values.size() != 2) {
+ return Option<bool>(400, format_err_msg);
+ }
+
+ if(dist_values[1] != "km" && dist_values[1] != "mi") {
+ return Option<bool>(400, "Unit must be either `km` or `mi`.");
+ }
+
+ processed_filter_val = filter_values[0] + ", " + filter_values[1] + ", " + // co-ords
+ dist_values[0] + ", " + dist_values[1]; // X km
+ }
return Option<bool>(true);
}
@@ -1950,7 +1974,8 @@ Option<bool> Collection::parse_filter_query(const std::string& simple_filter_que
f = {field_name, {}, {}};
const std::string& format_err_msg = "Value of filter field `" + _field.name +
- "`: must be in the `(-44.50, 170.29, 0.75 km)` format.";
+ "`: must be in the `(-44.50, 170.29, 0.75 km)` or "
+ "(56.33, -65.97, 23.82, -127.82) format.";
NUM_COMPARATOR num_comparator;
diff --git a/src/collection_manager.cpp b/src/collection_manager.cpp
index e2612819..26e91d94 100644
--- a/src/collection_manager.cpp
+++ b/src/collection_manager.cpp
@@ -25,8 +25,13 @@ Collection* CollectionManager::init_collection(const nlohmann::json & collection
field_obj[fields::optional] = false;
}
- fields.push_back({field_obj[fields::name], field_obj[fields::type],
- field_obj[fields::facet], field_obj[fields::optional]});
+ // handle older records indexed before geo_resolution field introduction
+ if(field_obj.count(fields::geo_resolution) == 0) {
+ field_obj[fields::geo_resolution] = size_t(DEFAULT_GEO_RESOLUTION);
+ }
+
+ fields.push_back({field_obj[fields::name], field_obj[fields::type], field_obj[fields::facet],
+ field_obj[fields::optional], field_obj[fields::geo_resolution]});
}
std::string default_sorting_field = collection_meta[Collection::COLLECTION_DEFAULT_SORTING_FIELD_KEY].get<std::string>();
diff --git a/src/index.cpp b/src/index.cpp
index 260dd447..0ada9e77 100644
--- a/src/index.cpp
+++ b/src/index.cpp
@@ -1072,79 +1072,147 @@ uint32_t Index::do_filtering(uint32_t** filter_ids_out, const std::vector<filter
}
} else if(f.is_geopoint()) {
- spp::sparse_hash_map<size_t, size_t> result_to_distance;
auto num_tree = numerical_index.at(a_filter.field_name);
- uint32_t* temp_ids = nullptr;
- size_t temp_ids_len = 0;
-
auto record_to_geo = sort_index.at(a_filter.field_name);
double indexed_edge_len = edgeLengthM(f.geo_resolution);
for(const std::string& filter_value: a_filter.values) {
std::vector<std::string> filter_value_parts;
- StringUtils::split(filter_value, filter_value_parts, " "); // x y 2 km
- double radius = std::stof(filter_value_parts[2]);
- const auto& unit = filter_value_parts[3];
+ StringUtils::split(filter_value, filter_value_parts, ","); // x, y, 2 km (or) list of points
+
+ std::vector<uint32_t> geo_result_ids;
+
+ bool is_polygon = StringUtils::is_float(filter_value_parts.back());
+
+ if(is_polygon) {
+ const int num_verts = int(filter_value_parts.size()) / 2;
+ GeoCoord* verts = new GeoCoord[num_verts];
+
+ for(size_t point_index = 0; point_index < size_t(num_verts); point_index++) {
+ double lat = degsToRads(std::stod(filter_value_parts[point_index * 2]));
+ double lon = degsToRads(std::stod(filter_value_parts[point_index * 2 + 1]));
+ verts[point_index] = {lat, lon};
+ }
+
+ Geofence geo_fence = {num_verts, verts};
+ GeoPolygon geo_polygon = {geo_fence, 0, nullptr};
+ double lon_offset = transform_for_180th_meridian(geo_fence);
+
+ size_t num_hexagons = maxPolyfillSize(&geo_polygon, f.geo_resolution);
+
+ H3Index* hexagons = static_cast<H3Index *>(calloc(num_hexagons, sizeof(H3Index)));
+
+ polyfill(&geo_polygon, f.geo_resolution, hexagons);
+
+ // we will have to expand by kring=1 to ensure that hexagons completely cover the polygon
+ // see: https://github.com/uber/h3/issues/332
+ std::set<uint64_t> expanded_hexagons;
+
+ for (size_t hex_index = 0; hex_index < num_hexagons; hex_index++) {
+ // Some indexes may be 0 to indicate fewer than the maximum number of indexes.
+ if (hexagons[hex_index] != 0) {
+ expanded_hexagons.emplace(hexagons[hex_index]);
+
+ size_t k_rings = 1;
+ size_t max_neighboring = maxKringSize(k_rings);
+ H3Index* neighboring_indices = static_cast<H3Index *>(calloc(max_neighboring, sizeof(H3Index)));
+ kRing(hexagons[hex_index], k_rings, neighboring_indices);
+
+ for (size_t neighbour_index = 0; neighbour_index < max_neighboring; neighbour_index++) {
+ if (neighboring_indices[neighbour_index] != 0) {
+ expanded_hexagons.emplace(neighboring_indices[neighbour_index]);
+ }
+ }
- if(unit == "km") {
- radius *= 1000;
+ free(neighboring_indices);
+ }
+ }
+
+ for(auto hex_id: expanded_hexagons) {
+ num_tree->get(hex_id, geo_result_ids);
+ }
+
+ // we will do an exact filtering again with point-in-poly checks
+ std::vector<uint32_t> exact_geo_result_ids;
+ for(auto result_id: geo_result_ids) {
+ GeoCoord point;
+ h3ToGeo(record_to_geo->at(result_id), &point);
+ point.lon = point.lon < 0.0 ? point.lon + lon_offset : point.lon;
+
+ if(is_point_in_polygon(geo_fence, point)) {
+ exact_geo_result_ids.push_back(result_id);
+ }
+ }
+
+ std::sort(exact_geo_result_ids.begin(), exact_geo_result_ids.end());
+
+ uint32_t *out = nullptr;
+ result_ids_len = ArrayUtils::or_scalar(&exact_geo_result_ids[0], exact_geo_result_ids.size(),
+ result_ids, result_ids_len, &out);
+
+ delete [] result_ids;
+ result_ids = out;
+
+ free(hexagons);
+ delete [] verts;
} else {
- // assume "mi" (validated upstream)
- radius *= 1609.34;
- }
+ double radius = std::stof(filter_value_parts[2]);
+ const auto& unit = filter_value_parts[3];
- GeoCoord location;
- location.lat = degsToRads(std::stod(filter_value_parts[0]));
- location.lon = degsToRads(std::stod(filter_value_parts[1]));
- H3Index query_index = geoToH3(&location, f.geo_resolution);
+ if(unit == "km") {
+ radius *= 1000;
+ } else {
+ // assume "mi" (validated upstream)
+ radius *= 1609.34;
+ }
- //LOG(INFO) << "query latlon: " << std::stod(filter_value_parts[0]) << ", " << std::stod(filter_value_parts[1]);
- //LOG(INFO) << "query h3 index: " << query_index << " at res: " << size_t(f.geo_resolution);
+ GeoCoord location;
+ location.lat = degsToRads(std::stod(filter_value_parts[0]));
+ location.lon = degsToRads(std::stod(filter_value_parts[1]));
+ H3Index query_index = geoToH3(&location, f.geo_resolution);
- size_t k_rings = size_t(std::ceil(radius / indexed_edge_len));
- size_t max_neighboring = maxKringSize(k_rings);
- H3Index* neighboring_indices = static_cast<H3Index *>(calloc(max_neighboring, sizeof(H3Index)));
- kRing(query_index, k_rings, neighboring_indices);
+ //LOG(INFO) << "query latlon: " << std::stod(filter_value_parts[0]) << ", " << std::stod(filter_value_parts[1]);
+ //LOG(INFO) << "query h3 index: " << query_index << " at res: " << size_t(f.geo_resolution);
- for (size_t hex_index = 0; hex_index < max_neighboring; hex_index++) {
- // Some indexes may be 0 to indicate fewer than the maximum number of indexes.
- if (neighboring_indices[hex_index] != 0) {
- //LOG(INFO) << "Neighbour index: " << neighboring_indices[hex_index];
- num_tree->search(EQUALS, neighboring_indices[hex_index], &temp_ids, temp_ids_len);
+ size_t k_rings = size_t(std::ceil(radius / indexed_edge_len));
+ size_t max_neighboring = maxKringSize(k_rings);
+ H3Index* neighboring_indices = static_cast<H3Index *>(calloc(max_neighboring, sizeof(H3Index)));
+ kRing(query_index, k_rings, neighboring_indices);
+
+ for (size_t hex_index = 0; hex_index < max_neighboring; hex_index++) {
+ // Some indexes may be 0 to indicate fewer than the maximum number of indexes.
+ if (neighboring_indices[hex_index] != 0) {
+ //LOG(INFO) << "Neighbour index: " << neighboring_indices[hex_index];
+ num_tree->get(neighboring_indices[hex_index], geo_result_ids);
+ }
}
- }
- free(neighboring_indices);
+ free(neighboring_indices);
- // `result_ids` will contain all IDs that are within K-ring hexagons
- // we still need to do another round of exact filtering on them
+ // `geo_result_ids` will contain all IDs that are within K-ring hexagons
+ // we still need to do another round of exact filtering on them
- H3Index query_point_index = geoToH3(&location, FINEST_GEO_RESOLUTION);
- for(size_t result_index = 0; result_index < temp_ids_len; result_index++) {
- uint32_t result_id = temp_ids[result_index];
- size_t actual_dist_meters = h3Distance(query_point_index, record_to_geo->at(result_id));
- if(actual_dist_meters <= radius) {
- auto it = result_to_distance.find(result_id);
- if(it == result_to_distance.end()) {
- result_to_distance.emplace(result_id, actual_dist_meters);
- } else {
- result_to_distance.emplace(result_id, std::min(actual_dist_meters, it->second));
+ std::vector<uint32_t> exact_geo_result_ids;
+
+ H3Index query_point_index = geoToH3(&location, FINEST_GEO_RESOLUTION);
+ for(auto result_id: geo_result_ids) {
+ size_t actual_dist_meters = h3Distance(query_point_index, record_to_geo->at(result_id));
+ if(actual_dist_meters <= radius) {
+ exact_geo_result_ids.push_back(result_id);
}
}
- }
- }
- result_ids = new uint32_t[result_to_distance.size()];
+ std::sort(exact_geo_result_ids.begin(), exact_geo_result_ids.end());
- // add IDs from `result_to_distance` to `result_ids`
- size_t kv_index = 0;
- for(const auto& kv: result_to_distance) {
- result_ids[kv_index++] = kv.first;
- }
+ uint32_t *out = nullptr;
+ result_ids_len = ArrayUtils::or_scalar(&exact_geo_result_ids[0], exact_geo_result_ids.size(),
+ result_ids, result_ids_len, &out);
- result_ids_len = result_to_distance.size();
- delete [] temp_ids;
+ delete [] result_ids;
+ result_ids = out;
+ }
+ }
} else if(f.is_string()) {
art_tree* t = search_index.at(a_filter.field_name);
@@ -2715,3 +2783,58 @@ void Index::get_doc_changes(const nlohmann::json &document, nlohmann::json &old_
}
}
}
+
+// https://stackoverflow.com/questions/924171/geo-fencing-point-inside-outside-polygon
+// NOTE: polygon and point should have been transformed with `transform_for_180th_meridian`
+bool Index::is_point_in_polygon(const Geofence& poly, const GeoCoord &point) {
+ int i, j;
+ bool c = false;
+
+ for (i = 0, j = poly.numVerts - 1; i < poly.numVerts; j = i++) {
+ if ((((poly.verts[i].lat <= point.lat) && (point.lat < poly.verts[j].lat))
+ || ((poly.verts[j].lat <= point.lat) && (point.lat < poly.verts[i].lat)))
+ && (point.lon < (poly.verts[j].lon - poly.verts[i].lon) * (point.lat - poly.verts[i].lat)
+ / (poly.verts[j].lat - poly.verts[i].lat) + poly.verts[i].lon)) {
+
+ c = !c;
+ }
+ }
+
+ return c;
+}
+
+double Index::transform_for_180th_meridian(Geofence &poly) {
+ double offset = 0.0;
+ double maxLon = -1000, minLon = 1000;
+
+ for(int v=0; v < poly.numVerts; v++) {
+ if(poly.verts[v].lon < minLon) {
+ minLon = poly.verts[v].lon;
+ }
+
+ if(poly.verts[v].lon > maxLon) {
+ maxLon = poly.verts[v].lon;
+ }
+
+ if(std::abs(minLon - maxLon) > 180) {
+ offset = 360.0;
+ }
+ }
+
+ int i, j;
+ for (i = 0, j = poly.numVerts - 1; i < poly.numVerts; j = i++) {
+ if (poly.verts[i].lon < 0.0) {
+ poly.verts[i].lon += offset;
+ }
+
+ if (poly.verts[j].lon < 0.0) {
+ poly.verts[j].lon += offset;
+ }
+ }
+
+ return offset;
+}
+
+void Index::transform_for_180th_meridian(GeoCoord &point, double offset) {
+ point.lon = point.lon < 0.0 ? point.lon + offset : point.lon;
+}
diff --git a/test/collection_all_fields_test.cpp b/test/collection_all_fields_test.cpp
index 7798005f..40a434d6 100644
--- a/test/collection_all_fields_test.cpp
+++ b/test/collection_all_fields_test.cpp
@@ -535,4 +535,20 @@ TEST_F(CollectionAllFieldsTest, JsonFieldsToFieldsConversion) {
parse_op = field::json_fields_to_fields(fields_json, fallback_field_type, fields);
ASSERT_TRUE(parse_op.ok());
ASSERT_EQ("auto", fields[0].type);
+
+ fields_json.clear();
+ all_field[fields::name] = "loc";
+ all_field[fields::type] = "geopoint";
+ all_field[fields::geo_resolution] = "blah";
+ fields_json.emplace_back(all_field);
+ parse_op = field::json_fields_to_fields(fields_json, fallback_field_type, fields);
+ ASSERT_FALSE(parse_op.ok());
+ ASSERT_EQ("The `geo_resolution` property of the field `loc` should be an integer.", parse_op.error());
+
+ fields_json.clear();
+ all_field[fields::geo_resolution] = 24;
+ fields_json.emplace_back(all_field);
+ parse_op = field::json_fields_to_fields(fields_json, fallback_field_type, fields);
+ ASSERT_FALSE(parse_op.ok());
+ ASSERT_EQ("The `geo_resolution` property of the field `loc` should be between 0 and 15.", parse_op.error());
}
diff --git a/test/collection_filtering_test.cpp b/test/collection_filtering_test.cpp
index 427c3cb8..82704872 100644
--- a/test/collection_filtering_test.cpp
+++ b/test/collection_filtering_test.cpp
@@ -4,6 +4,7 @@
#include <fstream>
#include <algorithm>
#include <collection_manager.h>
+#include <h3api.h>
#include "collection.h"
class CollectionFilteringTest : public ::testing::Test {
@@ -799,6 +800,66 @@ TEST_F(CollectionFilteringTest, GeoPointFiltering) {
collectionManager.drop_collection("coll1");
}
+TEST_F(CollectionFilteringTest, GeoPolygonFiltering) {
+ Collection *coll1;
+
+ std::vector<field> fields = {field("title", field_types::STRING, false),
+ field("loc", field_types::GEOPOINT, false),
+ field("points", field_types::INT32, false),};
+
+ coll1 = collectionManager.get_collection("coll1").get();
+ if(coll1 == nullptr) {
+ coll1 = collectionManager.create_collection("coll1", 1, fields, "points").get();
+ }
+
+ std::vector<std::vector<std::string>> records = {
+ {"Palais Garnier", "48.872576479306765, 2.332291112241466"},
+ {"Sacre Coeur", "48.888286721920934, 2.342340862419206"},
+ {"Arc de Triomphe", "48.87538726829884, 2.296113163780903"},
+ {"Place de la Concorde", "48.86536119187326, 2.321850747347093"},
+ {"Louvre Musuem", "48.86065813197502, 2.3381285349616725"},
+ {"Les Invalides", "48.856648379569904, 2.3118555692631357"},
+ {"Eiffel Tower", "48.85821022164442, 2.294239067890161"},
+ {"Notre-Dame de Paris", "48.852455825574495, 2.35071182406452"},
+ {"Musee Grevin", "48.872370541246816, 2.3431536410008906"},
+ {"Pantheon", "48.84620987789056, 2.345152755563131"},
+ };
+
+ for(size_t i=0; i<records.size(); i++) {
+ nlohmann::json doc;
+
+ std::vector<std::string> lat_lng;
+ StringUtils::split(records[i][1], lat_lng, ", ");
+
+ double lat = std::stod(lat_lng[0]);
+ double lng = std::stod(lat_lng[1]);
+
+ doc["id"] = std::to_string(i);
+ doc["title"] = records[i][0];
+ doc["loc"] = {lat, lng};
+ doc["points"] = i;
+
+ ASSERT_TRUE(coll1->add(doc.dump()).ok());
+ }
+
+ // pick a location close to only the Sacre Coeur
+ auto results = coll1->search("*",
+ {}, "loc: (48.875223042424125,2.323509661928681, "
+ "48.85745408145392, 2.3267084486160856, "
+ "48.859636574404355,2.351469427048221, "
+ "48.87756059389807, 2.3443610121873206)",
+ {}, {}, 0, 10, 1, FREQUENCY).get();
+
+ ASSERT_EQ(3, results["found"].get<size_t>());
+ ASSERT_EQ(3, results["hits"].size());
+
+ ASSERT_STREQ("8", results["hits"][0]["document"]["id"].get<std::string>().c_str());
+ ASSERT_STREQ("4", results["hits"][1]["document"]["id"].get<std::string>().c_str());
+ ASSERT_STREQ("0", results["hits"][2]["document"]["id"].get<std::string>().c_str());
+
+ collectionManager.drop_collection("coll1");
+}
+
TEST_F(CollectionFilteringTest, FilteringWithPrefixSearch) {
Collection *coll1;
diff --git a/test/collection_manager_test.cpp b/test/collection_manager_test.cpp
index fd7cd01c..e51757c0 100644
--- a/test/collection_manager_test.cpp
+++ b/test/collection_manager_test.cpp
@@ -24,10 +24,11 @@ protected:
collectionManager.load();
search_fields = {
- field("title", field_types::STRING, false),
- field("starring", field_types::STRING, false),
- field("cast", field_types::STRING_ARRAY, true, true),
- field("points", field_types::INT32, false)
+ field("title", field_types::STRING, false),
+ field("starring", field_types::STRING, false),
+ field("cast", field_types::STRING_ARRAY, true, true),
+ field("location", field_types::GEOPOINT, false, true, 14),
+ field("points", field_types::INT32, false)
};
sort_fields = { sort_by("points", "DESC") };
@@ -56,8 +57,9 @@ TEST_F(CollectionManagerTest, CollectionCreation) {
ASSERT_EQ(0, collection1->get_collection_id());
ASSERT_EQ(0, collection1->get_next_seq_id());
ASSERT_EQ(facet_fields_expected, collection1->get_facet_fields());
- ASSERT_EQ(1, collection1->get_sort_fields().size());
- ASSERT_EQ(sort_fields[0].name, collection1->get_sort_fields()[0].name);
+ ASSERT_EQ(2, collection1->get_sort_fields().size());
+ ASSERT_EQ("points", collection1->get_sort_fields()[0].name);
+ ASSERT_EQ("location", collection1->get_sort_fields()[1].name);
ASSERT_EQ(schema.size(), collection1->get_schema().size());
ASSERT_EQ("points", collection1->get_default_sorting_field());
@@ -86,6 +88,7 @@ TEST_F(CollectionManagerTest, CollectionCreation) {
"\"fields\":[{\"facet\":false,\"name\":\"title\",\"optional\":false,\"type\":\"string\"},"
"{\"facet\":false,\"name\":\"starring\",\"optional\":false,\"type\":\"string\"},"
"{\"facet\":true,\"name\":\"cast\",\"optional\":true,\"type\":\"string[]\"},"
+ "{\"facet\":false,\"geo_resolution\":14,\"name\":\"location\",\"optional\":true,\"type\":\"geopoint\"},"
"{\"facet\":false,\"name\":\"points\",\"optional\":false,\"type\":\"int32\"}],\"id\":0,"
"\"name\":\"collection1\",\"num_memory_shards\":4}",
collection_meta_json);
@@ -248,8 +251,9 @@ TEST_F(CollectionManagerTest, RestoreRecordsOnRestart) {
ASSERT_EQ(0, collection1->get_collection_id());
ASSERT_EQ(18, collection1->get_next_seq_id());
ASSERT_EQ(facet_fields_expected, collection1->get_facet_fields());
- ASSERT_EQ(1, collection1->get_sort_fields().size());
- ASSERT_EQ(sort_fields[0].name, collection1->get_sort_fields()[0].name);
+ ASSERT_EQ(2, collection1->get_sort_fields().size());
+ ASSERT_EQ("points", collection1->get_sort_fields()[0].name);
+ ASSERT_EQ("location", collection1->get_sort_fields()[1].name);
ASSERT_EQ(schema.size(), collection1->get_schema().size());
ASSERT_EQ("points", collection1->get_default_sorting_field());
diff --git a/test/index_test.cpp b/test/index_test.cpp
index 0cef0f21..c49358b0 100644
--- a/test/index_test.cpp
+++ b/test/index_test.cpp
@@ -56,4 +56,36 @@ TEST(IndexTest, ScrubReindexDoc) {
ASSERT_STREQ("1", del_doc3["id"].get<std::string>().c_str());
ASSERT_STREQ("The Lawyer", del_doc3["title"].get<std::string>().c_str());
ASSERT_STREQ("Bar", del_doc3["foo"].get<std::string>().c_str());
+}
+
+TEST(IndexTest, PointInPolygon180thMeridian) {
+ // somewhere in far eastern russia
+ GeoCoord verts[3] = {
+ {67.63378886620751, 179.87924212491276},
+ {67.6276069384328, -179.8364939577639},
+ {67.5749950728145, 179.94421673458666}
+ };
+
+ Geofence poly1{3, verts};
+ double offset = Index::transform_for_180th_meridian(poly1);
+
+ GeoCoord point1 = {67.61896440098865, 179.9998420463554};
+ GeoCoord point2 = {67.6332378896519, 179.88828622883355};
+ GeoCoord point3 = {67.62717271243574, -179.85954137693625};
+
+ GeoCoord point4 = {67.65842784263879, -179.79268650445243};
+ GeoCoord point5 = {67.62016647245217, 179.83764198608083};
+
+ Index::transform_for_180th_meridian(point1, offset);
+ Index::transform_for_180th_meridian(point2, offset);
+ Index::transform_for_180th_meridian(point3, offset);
+ Index::transform_for_180th_meridian(point4, offset);
+ Index::transform_for_180th_meridian(point5, offset);
+
+ ASSERT_TRUE(Index::is_point_in_polygon(poly1, point1));
+ ASSERT_TRUE(Index::is_point_in_polygon(poly1, point2));
+ ASSERT_TRUE(Index::is_point_in_polygon(poly1, point3));
+
+ ASSERT_FALSE(Index::is_point_in_polygon(poly1, point4));
+ ASSERT_FALSE(Index::is_point_in_polygon(poly1, point5));
}
\ No newline at end of file