如何为Pymongo时间序列中的元数据字段创建索引

问题描述 投票:0回答:1

我的时间序列对象:

{
    "timestamp": datetime object,
    "field1": "somestring",
    "metadata": {
        "type": 1,
        "location": "Hong Kong"
    }
}

我为我的

metadata
字段创建一个索引:

collection = db.create_collection(
    "market-catalog-time-series",
    timeseries={
        "timeField": "timestamp",
        "metaField": "metadata",
        "granularity": "seconds",
    },
)
db.collection.createIndex('metadata')

之后我想查询数据:

res = db.collection.find({"metadata": {"type": 1, "location": "Hong Kong"}})
print(list(res))

但是,我得到了

[]
,请问为什么?

mongodb pymongo
1个回答
0
投票

TL;DR:删除

db.
前缀,仅执行
res = collection.find(...)
db.get_collection("market-catalog-time-series").find(...)

说明:您正在创建一个名为

market-catalog-time-series
的集合,并将其分配给 变量
collection
。已经有一个来自
db.create_collection(...)
的父数据库。

但是在

res = db.collection.find(...)
中,它表示父数据库 collection
 名为 
db
集合。该集合可能不存在并且与您想要的不同。

db.collection.createIndex('metadata')
同样的问题。实际方法是
create_index()
而不是
createIndex()
。它应该只是
collection.create_index('metadata')
db.get_collection("market-catalog-time-series").create_index('metadata')

所以完整的代码是:

collection = db.create_collection(
    "market-catalog-time-series",
    timeseries={
        "timeField": "timestamp",
        "metaField": "metadata",
        "granularity": "seconds",
    },
)
collection.create_index('metadata')

res = collection.find({"metadata": {"type": 1, "location": "Hong Kong"}})
print(list(res))
© www.soinside.com 2019 - 2024. All rights reserved.