summaryrefslogtreecommitdiff
path: root/src/mongo/db/exec/2dnear.cpp
blob: d1f276c233a7eaa89a5c74bd7e6f281539900182 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
/**
 *    Copyright (C) 2013 10gen Inc.
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *    As a special exception, the copyright holders give permission to link the
 *    code of portions of this program with the OpenSSL library under certain
 *    conditions as described in each individual source file and distribute
 *    linked combinations including the program with the OpenSSL library. You
 *    must comply with the GNU Affero General Public License in all respects for
 *    all of the code used other than as permitted herein. If you modify file(s)
 *    with this exception, you may extend this exception to your version of the
 *    file(s), but you are not obligated to do so. If you do not wish to do so,
 *    delete this exception statement from your version. If you delete this
 *    exception statement from all source files in the program, then also delete
 *    it in the license file.
 */

#include "mongo/db/exec/2dnear.h"

#include "mongo/db/catalog/collection.h"
#include "mongo/db/catalog/database.h"
#include "mongo/db/client.h"
#include "mongo/db/exec/working_set_common.h"
#include "mongo/db/exec/working_set_computed_data.h"
#include "mongo/db/jsobj.h"

namespace mongo {

    // static
    const char* TwoDNear::kStageType = "GEO_NEAR_2D";

    TwoDNear::TwoDNear(const TwoDNearParams& params, WorkingSet* ws)
        : _commonStats(kStageType) {
        _params = params;
        _workingSet = ws;
        _initted = false;
    }

    TwoDNear::~TwoDNear() { }

    bool TwoDNear::isEOF() {
        return _initted && _results.empty();
    }

    PlanStage::StageState TwoDNear::work(WorkingSetID* out) {
        ++_commonStats.works;

        // Adds the amount of time taken by work() to executionTimeMillis.
        ScopedTimer timer(&_commonStats.executionTimeMillis);

        if (!_initted) {
            _initted = true;

            if ( !_params.collection )
                return PlanStage::IS_EOF;

            IndexCatalog* indexCatalog = _params.collection->getIndexCatalog();

            IndexDescriptor* desc = indexCatalog->findIndexByKeyPattern(_params.indexKeyPattern);
            if ( desc == NULL )
                return PlanStage::IS_EOF;
            TwoDAccessMethod* am = static_cast<TwoDAccessMethod*>( indexCatalog->getIndex( desc ) );

            auto_ptr<twod_exec::GeoSearch> search;
            search.reset(new twod_exec::GeoSearch(_params.collection,
                                           am,
                                           _params.nearQuery.centroid.oldPoint,
                                           _params.numWanted, 
                                           _params.filter,
                                           _params.nearQuery.maxDistance,
                                           _params.nearQuery.isNearSphere ? twod_exec::GEO_SPHERE
                                                                          : twod_exec::GEO_PLANE));

            // This is where all the work is done.  :(
            search->exec();
            _specificStats.objectsLoaded = search->_objectsLoaded;
            _specificStats.nscanned = search->_lookedAt;

            for (twod_exec::GeoHopper::Holder::iterator it = search->_points.begin();
                 it != search->_points.end(); it++) {

                WorkingSetID id = _workingSet->allocate();
                WorkingSetMember* member = _workingSet->get(id);
                member->loc = it->_loc;
                member->obj = _params.collection->docFor(member->loc);
                member->state = WorkingSetMember::LOC_AND_UNOWNED_OBJ;
                if (_params.addDistMeta) {
                    member->addComputed(new GeoDistanceComputedData(it->_distance));
                }
                if (_params.addPointMeta) {
                    member->addComputed(new GeoNearPointComputedData(it->_pt));
                }
                _results.push(Result(id, it->_distance));
                _invalidationMap.insert(pair<DiskLoc, WorkingSetID>(it->_loc, id));
            }
        }

        if (isEOF()) { return PlanStage::IS_EOF; }

        Result result = _results.top();
        _results.pop();
        *out = result.id;

        // Remove from invalidation map.
        WorkingSetMember* member = _workingSet->get(*out);

        // The WSM may have been mutated or deleted so it may not have a loc.
        if (member->hasLoc()) {
            typedef multimap<DiskLoc, WorkingSetID>::iterator MMIT;
            pair<MMIT, MMIT> range = _invalidationMap.equal_range(member->loc);
            for (MMIT it = range.first; it != range.second; ++it) {
                if (it->second == *out) {
                    _invalidationMap.erase(it);
                    break;
                }
            }
        }

        ++_commonStats.advanced;
        return PlanStage::ADVANCED;
    }

    void TwoDNear::prepareToYield() {
        // Nothing to do here.
    }

    void TwoDNear::recoverFromYield() {
        // Also nothing to do here.
    }

    void TwoDNear::invalidate(const DiskLoc& dl, InvalidationType type) {
        // We do the same thing for mutation or deletion: fetch the doc and forget about the
        // DiskLoc.  2d's near search computes all its results in one go so we know that we'll still
        // return valid data.
        typedef multimap<DiskLoc, WorkingSetID>::iterator MMIT;
        pair<MMIT, MMIT> range = _invalidationMap.equal_range(dl);
        for (MMIT it = range.first; it != range.second; ++it) {
            WorkingSetMember* member = _workingSet->get(it->second);
            // If it's in the invalidation map it must have a DiskLoc.
            verify(member->hasLoc());
            WorkingSetCommon::fetchAndInvalidateLoc(member, _params.collection);
            verify(!member->hasLoc());
        }
        _invalidationMap.erase(range.first, range.second);
    }

    vector<PlanStage*> TwoDNear::getChildren() const {
        vector<PlanStage*> empty;
        return empty;
    }

    PlanStageStats* TwoDNear::getStats() {
        _commonStats.isEOF = isEOF();
        _specificStats.keyPattern = _params.indexKeyPattern;
        auto_ptr<PlanStageStats> ret(new PlanStageStats(_commonStats, STAGE_GEO_NEAR_2D));
        ret->specific.reset(new TwoDNearStats(_specificStats));
        return ret.release();
    }

}  // namespace mongo

namespace mongo {
namespace twod_exec {

    //
    // GeoHopper
    //

    GeoHopper::GeoHopper(Collection* collection,
             TwoDAccessMethod* accessMethod,
            unsigned max,
            const Point& n,
            MatchExpression* filter,
            double maxDistance,
            GeoDistType type)
        : GeoBrowse(collection, accessMethod, "search", filter),
        _max(max),
        _near(n),
        _maxDistance(maxDistance),
        _type(type),
        _distError(type == GEO_PLANE
                ? accessMethod->getParams().geoHashConverter->getError()
                : accessMethod->getParams().geoHashConverter->getErrorSphere()),
        _farthest(0),
        _collection(collection) {}

    GeoAccumulator:: KeyResult GeoHopper::approxKeyCheck(const Point& p, double& d) {
        // Always check approximate distance, since it lets us avoid doing
        // checks of the rest of the object if it succeeds
        switch (_type) {
            case GEO_PLANE:
                d = distance(_near, p);
                break;
            case GEO_SPHERE:
                checkEarthBounds(p);
                d = spheredist_deg(_near, p);
                break;
            default: verify(false);
        }
        verify(d >= 0);

        // If we need more points
        double borderDist = (_points.size() < _max ? _maxDistance : farthest());

        if (d >= borderDist - 2 * _distError && d <= borderDist + 2 * _distError) return BORDER;
        else return d < borderDist ? GOOD : BAD;
    }

    bool GeoHopper::exactDocCheck(const Point& p, double& d){
        bool within = false;

        // Get the appropriate distance for the type
        switch (_type) {
            case GEO_PLANE:
                d = distance(_near, p);
                within = distanceWithin(_near, p, _maxDistance);
                break;
            case GEO_SPHERE:
                checkEarthBounds(p);
                d = spheredist_deg(_near, p);
                within = (d <= _maxDistance);
                break;
            default: verify(false);
        }

        return within;
    }


    int GeoHopper::addSpecific(const GeoIndexEntry& node, const Point& keyP, bool onBounds,
            double keyD, bool potentiallyNewDoc) {
        // Unique documents
        GeoPoint newPoint(node, _collection->docFor(node.recordLoc), keyD, false);
        int prevSize = _points.size();

        // STEP 1 : Remove old duplicate points from the set if needed

        // Lookup old point with same doc
        map<DiskLoc, Holder::iterator>::iterator oldPointIt = _seenPts.find(newPoint.loc());

        if(oldPointIt != _seenPts.end()){
            const GeoPoint& oldPoint = *(oldPointIt->second);
            // We don't need to care if we've already seen this same approx pt or better,
            // or we've already gone to disk once for the point
            if(oldPoint < newPoint){
                return 0;
            }
            _points.erase(oldPointIt->second);
        }

        //cout << "inserting point\n";
        Holder::iterator newIt = _points.insert(newPoint);
        _seenPts[ newPoint.loc() ] = newIt;

        verify(_max > 0);

        Holder::iterator lastPtIt = _points.end();
        lastPtIt--;
        _farthest = lastPtIt->distance() + 2 * _distError;
        return _points.size() - prevSize;
    }

    // Removes extra points from end of _points set.
    // Check can be a bit costly if we have lots of exact points near borders,
    // so we'll do this every once and awhile.
    void GeoHopper::processExtraPoints(){
        if(_points.size() == 0) return;
        int prevSize = _points.size();

        // Erase all points from the set with a position >= _max *and*
        // whose distance isn't close to the _max - 1 position distance
        int numToErase = _points.size() - _max;
        if(numToErase < 0) numToErase = 0;

        // Get the first point definitely in the _points array
        Holder::iterator startErase = _points.end();
        for(int i = 0; i < numToErase + 1; i++) startErase--;
        _farthest = startErase->distance() + 2 * _distError;

        startErase++;
        while(numToErase > 0 && startErase->distance() <= _farthest){
            numToErase--;
            startErase++;
            verify(startErase != _points.end() || numToErase == 0);
        }

        for(Holder::iterator i = startErase; i != _points.end(); ++i) {
            _seenPts.erase(i->loc());
        }

        _points.erase(startErase, _points.end());

        int diff = _points.size() - prevSize;
        if(diff > 0) _found += diff;
        else _found -= -diff;
    }

    //
    // GeoSearch
    //

    GeoSearch::GeoSearch(Collection* collection,
            TwoDAccessMethod* accessMethod,
            const Point& startPt,
            int numWanted,
            MatchExpression* filter,
            double maxDistance,
            GeoDistType type)
        : GeoHopper(collection, accessMethod, numWanted, startPt, filter, maxDistance, type),
        _start(accessMethod->getParams().geoHashConverter->hash(startPt.x, startPt.y)),
        _numWanted(numWanted),
        _type(type),
        _params(accessMethod->getParams()) {

            _nscanned = 0;
            _found = 0;

            if(_maxDistance < 0){
                _scanDistance = numeric_limits<double>::max();
            } else if (type == GEO_PLANE) {
                _scanDistance = maxDistance + _params.geoHashConverter->getError();
            } else if (type == GEO_SPHERE) {
                checkEarthBounds(startPt);
                // TODO: consider splitting into x and y scan distances
                _scanDistance = computeXScanDistance(startPt.y,
                        rad2deg(_maxDistance) + _params.geoHashConverter->getError());
            }

            verify(_scanDistance > 0);
        }

    void GeoSearch::exec() {
        if(_numWanted == 0) return;

        /*
         * Search algorithm
         * 1) use geohash prefix to find X items
         * 2) compute max distance from want to an item
         * 3) find optimal set of boxes that complete circle
         * 4) use regular btree cursors to scan those boxes
         */

        // Part 1
        {
            do {
                long long f = found();
                verify(f <= 0x7fffffff);
                fillStack(maxPointsHeuristic, _numWanted - static_cast<int>(f), true);
                processExtraPoints();
            } while(_state != DONE && _state != DONE_NEIGHBOR &&
                    found() < _numWanted &&
                    (!_prefix.constrains() ||
                     _params.geoHashConverter->sizeEdge(_prefix) <= _scanDistance));

            // If we couldn't scan or scanned everything, we're done
            if(_state == DONE){
                expandEndPoints();
                return;
            }
        }

        // Part 2
        {
            // Find farthest distance for completion scan
            double farDist = farthest();
            if(found() < _numWanted) {
                // Not enough found in Phase 1
                farDist = _scanDistance;
            }
            else if (_type == GEO_PLANE) {
                // Enough found, but need to search neighbor boxes
                farDist += _params.geoHashConverter->getError();
            }
            else if (_type == GEO_SPHERE) {
                // Enough found, but need to search neighbor boxes
                farDist = std::min(_scanDistance,
                        computeXScanDistance(_near.y,
                            rad2deg(farDist))
                        + 2 * _params.geoHashConverter->getError());
            }
            verify(farDist >= 0);

            // Find the box that includes all the points we need to return
            _want = Box(_near.x - farDist, _near.y - farDist, farDist * 2);

            // Remember the far distance for further scans
            _scanDistance = farDist;

            // Reset the search, our distances have probably changed
            if(_state == DONE_NEIGHBOR){
                _state = DOING_EXPAND;
                _neighbor = -1;
            }

            // Do regular search in the full region
            do {
                fillStack(maxPointsHeuristic);
                processExtraPoints();
            }
            while(_state != DONE);
        }

        expandEndPoints();
    }

    void GeoSearch::addExactPoints(const GeoPoint& pt, Holder& points, bool force){
        int before, after;
        addExactPoints(pt, points, before, after, force);
    }

    void GeoSearch::addExactPoints(const GeoPoint& pt, Holder& points, int& before, int& after,
            bool force){
        before = 0;
        after = 0;

        if(pt.isExact()){
            if(force) points.insert(pt);
            return;
        }

        vector<BSONObj> locs;
        // last argument is uniqueDocs
        getPointsFor(pt.key(), pt.obj(), locs, true);

        GeoPoint nearestPt(pt, -1, true);

        for(vector<BSONObj>::iterator i = locs.begin(); i != locs.end(); i++){
            Point loc(*i);
            double d;
            if(! exactDocCheck(loc, d)) continue;

            if(nearestPt.distance() < 0 || d < nearestPt.distance()){
                nearestPt._distance = d;
                nearestPt._pt = *i;
                continue;
            }
        }

        if(nearestPt.distance() >= 0){
            points.insert(nearestPt);
            if(nearestPt < pt) before++;
            else after++;
        }
    }

    // TODO: Refactor this back into holder class, allow to run periodically when we are seeing
    // a lot of pts
    void GeoSearch::expandEndPoints(bool finish) {
        processExtraPoints();
        // All points in array *could* be in maxDistance

        // Step 1 : Trim points to max size TODO:  This check will do little for now, but is
        // skeleton for future work in incremental $near
        // searches
        if(_max > 0){
            int numToErase = _points.size() - _max;
            if(numToErase > 0){
                Holder tested;
                // Work backward through all points we're not sure belong in the set
                Holder::iterator maybePointIt = _points.end();
                maybePointIt--;
                double approxMin = maybePointIt->distance() - 2 * _distError;

                // Insert all
                int erased = 0;
                while(_points.size() > 0
                        && (maybePointIt->distance() >= approxMin || erased < numToErase)){

                    Holder::iterator current = maybePointIt;
                    if (current != _points.begin())
                        --maybePointIt;

                    addExactPoints(*current, tested, true);
                    _points.erase(current);
                    erased++;

                    if(tested.size())
                        approxMin = tested.begin()->distance() - 2 * _distError;
                }

                int numToAddBack = erased - numToErase;
                verify(numToAddBack >= 0);

                Holder::iterator testedIt = tested.begin();
                for(int i = 0; i < numToAddBack && testedIt != tested.end(); i++){
                    _points.insert(*testedIt);
                    testedIt++;
                }
            }
        }

        // We've now trimmed first set of unneeded points

        // Step 2: iterate through all points and add as needed
        unsigned expandedPoints = 0;
        Holder::iterator it = _points.begin();
        double expandWindowEnd = -1;

        while(it != _points.end()){
            const GeoPoint& currPt = *it;
            // TODO: If one point is exact, maybe not 2 * _distError

            // See if we're in an expand window
            bool inWindow = currPt.distance() <= expandWindowEnd;
            // If we're not, and we're done with points, break
            if(! inWindow && expandedPoints >= _max) break;

            bool expandApprox = !currPt.isExact() && (finish || inWindow);

            if (expandApprox) {
                // Add new point(s). These will only be added in a radius of 2 * _distError
                // around the current point, so should not affect previously valid points.
                int before, after;
                addExactPoints(currPt, _points, before, after, false);
                expandedPoints += before;

                if(_max > 0 && expandedPoints < _max)
                    expandWindowEnd = currPt.distance() + 2 * _distError;

                // Iterate to the next point
                Holder::iterator current = it++;
                // Erase the current point
                _points.erase(current);
            } else{
                expandedPoints++;
                it++;
            }
        }

        // Finish
        // TODO:  Don't really need to trim?
        for(; expandedPoints > _max; expandedPoints--) it--;
        _points.erase(it, _points.end());
    }

}  // namespace twod_exec
}  // namespace mongo