CosmosDB地理空间查询不返回任何内容

时间:2017-12-21 00:38:15

标签: node.js mongodb azure azure-cosmosdb

我正在使用MongoDB界面探索Azure的CosmosDB。我写了以下测试(使用Jest)。我的大多数其他测试我都可以将MongoDB网址交换为CosmosDB网址,它们会运行并通过。当指向MongoDB并且使用CosmosDB url失败时,此测试通过:

const { MongoClient } = require('mongodb')

let client, db, collection
const url = 'mongodb://localhost:27017'
const dbName = 'test'
describe('talking to mongodb', () => {
  beforeEach(async () => {
    client = await MongoClient.connect(url)
    db = client.db(dbName)
    collection = db.collection('cities')
    await collection.createIndex({ location: '2dsphere' })
  })

  afterEach(async () => {
    await collection.drop()
    client.close()
  })

  it('it can find geocoded things', async () => {
    await collection.insertMany([
      {
        city: 'Ottawa, Canada',
        location: {
          type: 'Point',
          coordinates: [-75.69719309999999, 45.4215296],
        },
        bbox: [-76.35391589999999, 44.962733, -75.2465979, 45.5375801],
      },
      {
        city: 'Moscow, Russia',
        location: { type: 'Point', coordinates: [37.6172999, 55.755826] },
        bbox: [37.3193289, 55.48992699999999, 37.9456611, 56.009657],
      },
    ])

    let cursor = await collection.find({
      location: {
        $near: { type: 'Point', coordinates: [-79.3831843, 43.653226] },
        $maxDistance: 500000,
      },
    })
    let [doc] = await cursor.toArray()

    expect(doc.city).toEqual('Ottawa, Canada')
  })
})

此测试失败,出现以下错误:

  ● talking to mongodb › it can find geocoded things

    MongoError: Request is malformed

      at node_modules/mongodb-core/lib/cursor.js:769:34
      at handleCallback (node_modules/mongodb-core/lib/cursor.js:178:5)
      at setCursorDeadAndNotified (node_modules/mongodb-core/lib/cursor.js:545:3)
      at nextFunction (node_modules/mongodb-core/lib/cursor.js:768:14)
      at node_modules/mongodb-core/lib/cursor.js:665:7
      at queryCallback (node_modules/mongodb-core/lib/cursor.js:263:5)
      at node_modules/mongodb-core/lib/connection/pool.js:542:18

请记住,该查询在MongoDB中有效。稍微修改一下,我可以获得一个在MongoDB中工作的查询,并且不会在CosmosDB中生成错误:

db.cities.find({"location": { $near:{ $geometry: { type: "Point", coordinates: [-79.3831843, 43.653226] }, $maxDistance: 500000 }}})

但是该查询在CosmosDB上没有返回任何内容。

我需要做些什么才能让该查询返回结果并将测试传递给CosmosDB?

1 个答案:

答案 0 :(得分:0)

基于the docthis post,Azure Cosmos DB会自动为每个字段创建索引。因此,您不再需要在Node.js代码中创建位置索引。

如果在不创建任何索引的情况下重新创建集合,这将起作用:

enter image description here

另见:

Geospatial index querying doesn't work on Azure CosmosDB (DocumentDB) using the Mongo API