feat: Add K-Nearest Neighbor (<->) operator for blazing fast spatial searches#6
Merged
Conversation
…searches - Added the PostGIS <-> operator (K-Nearest Neighbor) to Arel - This operator uses spatial indexes for incredibly fast 'find nearest' queries - Much faster than ST_Distance + ORDER BY for finding closest geometries - Added comprehensive tests for the new operator - Updated documentation with space combat examples showing tactical uses The <-> operator is a game-changer for performance when finding nearest: - Restaurants, stores, or locations - Ships, satellites, or space stations - Any spatial objects where you need the N closest items Example usage: Location.order(Location.arel_table[:position].distance_operator(origin)).limit(10)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
This PR adds the PostGIS K-Nearest Neighbor (
<->) operator to the gem, enabling lightning-fast spatial searches that utilize spatial indexes.Why This Matters
Traditional "find nearest" queries using
ST_Distance+ORDER BYscan the entire table and calculate distances for every row. The<->operator uses spatial indexes to return results orders of magnitude faster.Implementation
New Arel Methods
distance_operator(geometry)- The primary method for KNN searches:<->alias - For those who prefer symbolic operatorsUsage Examples
Performance Impact
The
<->operator can be 100-1000x faster than traditional distance queries for large datasets because it uses the spatial index directly rather than calculating distances for every row.Documentation
Updated both the technical documentation and the space-themed guides with examples of tactical uses for the KNN operator.
That's it folks! This completes the extraction of custom spatial code I had in my projects. Any additional features can be added via PRs with tests.