地理空间搜索
为了支持地理空间查询,MongoDB 提供了地理空间索引和地理空间查询操作符。
要了解有关执行地理空间查询的更多信息,请参阅地理空间查询 服务器手册。
先决条件
您必须设置以下组件以运行本指南中的代码示例
A
test.restaurants
集合用来自restaurants.json
文件的文档填充,该文件位于 文档资源 GitHub。以下导入语句
import com.mongodb.reactivestreams.client.MongoClients; import com.mongodb.reactivestreams.client.MongoClient; import com.mongodb.reactivestreams.client.MongoCollection; import com.mongodb.reactivestreams.client.MongoDatabase; import com.mongodb.client.model.geojson.*; import com.mongodb.client.model.Indexes; import com.mongodb.client.model.Filters; import org.bson.Document;
重要
本指南使用自定义 Subscriber
实现,这些实现在本指南中描述。示例自定义订阅者实现
连接到 MongoDB 部署
首先,连接到 MongoDB 部署,然后声明并定义 MongoDatabase
和 MongoCollection
实例。
以下代码连接到在本地主机 localhost
的端口 27017
上运行的独立 MongoDB 部署。然后,它定义了 database
变量来引用 test
数据库,以及 collection
变量来引用 restaurants
集合。
MongoClient mongoClient = MongoClients.create(); MongoDatabase database = mongoClient.getDatabase("test"); MongoCollection<Document> collection = database.getCollection("restaurants");
要了解更多关于连接到 MongoDB 部署的信息,请参阅连接到 MongoDB 教程。
创建 2dsphere 索引
要创建 2dsphere
索引,使用 Indexes.geo2dsphere()
辅助函数创建 2dsphere
索引的规范。将规范传递给 MongoCollection.createIndex()
方法以创建索引。
以下示例在 restaurants
集合的 "contact.location"
字段上创建 2dsphere
索引。
MongoCollection<Document> collection = database.getCollection("restaurants"); collection.createIndex(Indexes.geo2dsphere("contact.location")) .subscribe(new PrintSubscriber<String>());
在GeoJSON点附近查询位置
MongoDB提供了各种地理空间查询运算符。为了方便创建地理空间查询过滤器,驱动程序提供了Filters
类和com.mongodb.client.model.geojson
包。
以下示例返回至少1000米且最多5000米距离指定GeoJSON Point
实例的文档,按从近到远排序
Point refPoint = new Point(new Position(-73.9667, 40.78)); collection.find(Filters.near("contact.location", refPoint, 5000.0, 1000.0)) .subscribe(new PrintDocumentSubscriber());