Skip to content

Instantly share code, notes, and snippets.

@focusj
Last active August 29, 2015 14:01
Show Gist options
  • Save focusj/2bfd6384e588aec3d501 to your computer and use it in GitHub Desktop.
Save focusj/2bfd6384e588aec3d501 to your computer and use it in GitHub Desktop.
Example for testing MongoDB GeoIndex
mport com.mongodb.{Mongo, BasicDBObject, DBObject}
import scala.collection.convert.WrapAsJava
object Test extends App with WrapAsJava {
val mongo = new Mongo("host").getDB("TestGeoDB").getCollection("city")
private val line2Bson: String => DBObject = line => {
val Array(_id, country, city, lati, longi, elevation) = line.split(";").map(_.replace("\"", ""))
new BasicDBObject(
mapAsJavaMap(Map(
"_id" -> _id.toInt,
"country" -> country.toString,
"city" -> city.toString,
"loc" -> new BasicDBObject(
mapAsJavaMap(Map(
"type" -> "Point",
"coordinates" -> Array(longi.toDouble, lati.toDouble)
))),
"ele" -> elevation.toDouble
)))
}
//Insert
/*Source.fromFile(
new File("/home/focusj/Git/ScalaSpec/src/main/resources/World_Cities_Location_table.csv")
).getLines.map(l => line2Bson(l)).grouped(40).foreach{ docs => mongo.insert(docs)}*/
//LanZhou: 103.7922211, 36.0563889
//ShangHai: 121.4580536, 31.2222222
val query1 = new BasicDBObject(
mapAsJavaMap(Map(
"loc" -> new BasicDBObject(
mapAsJavaMap(
Map("$geoWithin" -> new BasicDBObject(
mapAsJavaMap(
Map("$centerSphere" -> Array(Array(103.7922211, 36.0563889), 1000 / 111.2))
)))
)
)
))
)
// { <location field> :
// { $near :
// { $geometry :
// { type : "Point" ,
// coordinates : [ <longitude> , <latitude> ] } ,
// $maxDistance : <distance in meters>
// } } }
val query2 = new BasicDBObject(
mapAsJavaMap(Map(
"loc" -> new BasicDBObject(
mapAsJavaMap(
Map("$near" -> new BasicDBObject(
mapAsJavaMap(Map("$geometry" -> new BasicDBObject(
mapAsJavaMap(
Map("type" -> "Point",
"coordinates" -> Array(121.4580536, 31.2222222)
))),
"$maxDistance" -> 2000000)))))))))
val r = mongo.find(query2)
// while (r.hasNext) {
// val obj = r.next()
// println(
// obj.get("_id"),
// obj.get("country"),
// obj.get("city"))
// }
println(r.size())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment