MongoDB 3.4rc z 2mln rekordów
Myślę, że problem z Twoim kodem jest związany z parametrem „zapytanie”, ponieważ tworzysz kolejne zapytanie w Kolekcji bez indeksu.
AKTUALIZACJA (z wynikami/statystykami):
db.runCommand( { dropDatabase: 1 } )
db.createCollection("places");
db.places.createIndex( { "locs.loc.coordinates" : "2dsphere" } )
function randInt(n) { return parseInt(Math.random()*n); }
function randFloat(n) { return Math.random()*n; }
for(var j=0; j<10; j++) {
print("Building op "+j);
var bulkop=db.places.initializeOrderedBulkOp() ;
for (var i = 0; i < 1000000; ++i) {
bulkop.insert(
{
locs: [
{
loc : {
type: "Point",
coordinates: [ randFloat(180), randFloat(90) ]
}
},
{
loc : {
coordinates: [ randFloat(180), randFloat(90) ]
}
}
]
}
)
};
print("Executing op "+j);
bulkop.execute();
}
Oto zapytanie:
db.runCommand(
{
geoNear: "places",
near: { type: "Point", coordinates: [ 73.9667, 40.78 ] },
spherical: true
}
)
db.runCommand(
{
geoNear: "places",
near: { type: "Point", coordinates: [ 73.9667, 40.78 ] },
spherical: true,
query: { category: "private" }
}
)
Po utworzeniu "kategorii" index:{ locs.loc.coordinates:"2dsphere", kategoria:1 }
AKTUALIZACJA: dodając „maxDistance” możesz wykonać 396ms w porównaniu z 6863 ms
db.runCommand(
{
geoNear: "places",
near: { type: "Point", coordinates: [ 73.9667, 40.78 ] },
spherical: true,
query: {category: "private"},
maxDistance: 1000000
}
)
maxDistance:1000000
"stats" : {
"nscanned" : NumberInt(107820),
"objectsLoaded" : NumberInt(1),
"avgDistance" : 938598.1782650856,
"maxDistance" : 938598.1782650856,
"time" : NumberInt(396)
}
bez "maxDistance":
db.runCommand(
{
geoNear: "places",
near: { type: "Point", coordinates: [ 73.9667, 40.78 ] },
spherical: true,
query: {category: "private"}
}
)
"stats" : {
"nscanned" : NumberInt(2023916),
"objectsLoaded" : NumberInt(6),
"avgDistance" : 3013587.205365039,
"maxDistance" : 4263919.742779636,
"time" : NumberInt(6863)
}
Źródło:https://www.mongodb .com/blog/post/geospatial-performance-improvements-in-mongodb-3-2
Co więcej, twoje zapytanie używa „tablicy współrzędnych”, co moim zdaniem jest bezużyteczne, ponieważ jeden obiekt (ogólnie) ma 1 punkt geolokalizacji.
Innym sposobem optymalizacji jest utworzenie „geoWithin " ponieważ nie sortuje według "odległości" (może chcesz posortować według "najczęściej głosowanej restauracji"). W zależności od scenariusza.