簡體   English   中英

使用Doctrine MongoDB ODM進行地理空間查詢

[英]Geo spatial queries with Doctrine MongoDB ODM

我在文檔的坐標屬性上有一個二維索引。 使用mongo shell,我可以這樣查詢集合:

db.adverts.find({coordinates:{$near:[20,40]}})

並按預期返回以下結果;

{ "_id" : ObjectId("4fddac51352de93903000000"), "title" : "dummy #3", "coordinates" : { "longitude" : 22, "latitude" : 31 } }
{ "_id" : ObjectId("4fddac48352de95105000000"), "title" : "dummy #3", "coordinates" : { "longitude" : 20, "latitude" : 30 } }
{ "_id" : ObjectId("4fddaca4352de93703000000"), "title" : "dummy #3", "coordinates" : { "longitude" : 31, "latitude" : 22 } }
{ "_id" : ObjectId("4fdda6a2352de90a03000000"), "title" : "dummy title", "created" : ISODate("2012-06-17T09:42:58Z"), "coordinates" : { "longitude" : 54.1234, "latitude" : -1.234 } }
{ "_id" : ObjectId("4fdda6d8352de9c004000000"), "title" : "dummy title #2", "created" : ISODate("2012-06-17T09:43:52Z"), "coordinates" : { "longitude" : 54.34, "latitude" : -1.124 } }

但是,根據文檔使用Doctrine查詢完全相同的集合,我沒有得到任何結果,例如

$adverts = $dm->createQueryBuilder('Advert')
                      ->field('coordinates')->near(20, 40)
                      ->getQuery()
                      ->execute();
$adverts->count(); // => 0

我的廣告Yaml看起來像這樣;

Advert:
    type: document
    collection: adverts
    fields:
        id:
            id: true
        title:
            type: string
        content:
            type: string
        created:
            type: date
        updated:
            type: date
        status:
            type: int
        distance:
            type: int

    indexes:
        coordinates:
            keys:
                coordinates: 2d

    referenceOne:
        owner:
            targetDocument: User

    embedOne:
        coordinates:
            targetDocument: Coordinates

坐標文件就是這樣;

Coordinates:
    type: embeddedDocument
    fields:
        longitude:
            type: float
        latitude:
            type: float

有什么想法為什么使用Doctrine的ODM會對同一查詢返回零結果?

更新#1似乎Doctrine \\ MongoDB \\ Query \\ Builder :: near()L363有問題。 method參數忽略第二個值($ y)。 因此,只有第一個值被傳遞才能執行。

near()方法似乎存在一個實現問題(請參閱https://github.com/doctrine/mongodb/pull/53 )。 要解決原始查詢,我需要執行以下操作;

$adverts = $dm->createQueryBuilder('Advert')
              ->field('coordinates.latitude')->near(20)
              ->field('coordinates.longitude')->near(40);

$adverts->getQuery()->count(); // => 5

這與當前的文檔矛盾,后者暗示可以將x,y坐標都傳遞給Doctrine \\ MongoDB \\ Query \\ Builder :: near()。

編輯

為了使生活更輕松,我創建了一個自定義存儲庫類,以為這種不一致提供更直觀的解決方案。

public function near($longitude, $latitude)
{
    $query = $this->createQueryBuilder()
                  ->field('coordinates.longitude')->near((float) $longitude)
                  ->field('coordinates.latitude')->near((float) $latitude)
                  ->getQuery();

    return $query;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM