我从mongoose创建了这个集合:
var ethTransactionSchema = new mongoose.Schema({
blockNumber: Number,
blockHash: String,
hash: String,
transactionIndex: Number,
from: String,
to: String,
value: String
});
ethTransactionSchema.index({ hash: 1 }, { unique: true });
ethTransactionSchema.index({ from: 1 });
ethTransactionSchema.index({ to: 1 });
ethTransactionSchema.index({ blockNumber: 1, transactionIndex: 1 });
ethTransactionSchema.index({ from: 1, to: 1, blockNumber: 1, transactionIndex: 1 });
ethTransactionSchema.index({ from: 1, blockNumber: 1, transactionIndex: 1});
ethTransactionSchema.index({ to: 1, blockNumber: 1, transactionIndex: 1 });
ethTransactionSchema.index({ to: 1, blockNumber: 1 });
ethTransactionSchema.index({ from: 1, blockNumber: 1 });
ethTransactionSchema.index({ from: 1, to: 1, blockNumber: 1 });
ethTransactionSchema.index({ blockNumber: 1 });
ethTransactionSchema.index({ transactionIndex: 1 });
ethTransactionSchema.index({ blockNumber: -1 });
ethTransactionSchema.index({ to: 1, blockNumber: -1 });
ethTransactionSchema.index({ from: 1, blockNumber: -1 });
ethTransactionSchema.index({ from: 1, to: 1, blockNumber: -1 });
ethTransactionSchema.index({ from: 1, to: 1, blockNumber: -1, transactionIndex: -1 });
ethTransactionSchema.index({ from: 1, blockNumber: -1, transactionIndex: -1 });
ethTransactionSchema.index({ to: 1, blockNumber: -1, transactionIndex: -1 });
如果我执行此查询:
find({$or: [from: '0x120a270bbc009644e35f0bb6ab13f95b8199c4ad',
to: '0x120a270bbc009644e35f0bb6ab13f95b8199c4ad'
]})
.sort({blockNumber: -1, transactionIndex: -1}).limit(20)
我获得了出色的表现:
It chooses these indexes (from explain())
{
"from" : 1,
"blockNumber" : 1,
"transactionIndex" : 1
}
{
"to" : 1,
"blockNumber" : 1,
"transactionIndex" : 1
}
但是在执行此查询时:
find({$and: [{$or: [{from: '0x120a270bbc009644e35f0bb6ab13f95b8199c4ad'},
{to: '0x120a270bbc009644e35f0bb6ab13f95b8199c4ad'}
]},
{blockNumber: {$lte: 1700000}}
]}).sort({blockNumber:-1, transactionIndex: -1}).limit(21)
我的表现不佳,有时返回结果需要20多秒(大多数时间不到一秒)。它选择这些索引:
{
"from": 1
{
{
"to": 1
}
如果时间可以在不到一秒的时间内预测,那么这是可以接受的,但第一次查询需要花费20或30秒的时间,这是完全不可接受的。 从Mongo Shell执行相同的查询我得到相同的结果。
有人能指出我的解决方案吗?
感谢先进, P /
答案 0 :(得分:0)
试试这个
find().lean()
精益命令以普通对象的形式给出结果。它会提高性能。
答案 1 :(得分:0)
我找到了问题的解决方法。无法使$或查询正常工作。我将查询缩减为:
find({$and: [{from: '0x120a270bbc009644e35f0bb6ab13f95b8199c4ad'},
{blockNumber: {$lte: 1700000}}
]}).sort({blockNumber:-1, transactionIndex: -1}).limit(21)
和:
find({$and: [{to: '0x120a270bbc009644e35f0bb6ab13f95b8199c4ad'},
{blockNumber: {$lte: 1700000}}
]}).sort({blockNumber:-1, transactionIndex: -1}).limit(21)
然后我自己合并结果。它现在工作得很好,但我认为我使用的是真正的数据库,可能是我的错。这个数据库只是玩,如果你尝试复杂的查询,它就不够好。