本文整理汇总了Python中txmongo.filter.sort函数的典型用法代码示例。如果您正苦于以下问题:Python sort函数的具体用法?Python sort怎么用?Python sort使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了sort函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_index_info
def test_index_info(self):
db = self.db
yield db.test.drop_indexes()
yield db.test.remove({})
db.test.save({}) # create collection
ix_info = yield db.test.index_information()
self.assertEqual(len(ix_info), 1)
self.assertEqual(ix_info["_id_"]["name"], "_id_")
yield db.test.create_index(filter.sort(filter.ASCENDING("hello")))
ix_info = yield db.test.index_information()
self.assertEqual(len(ix_info), 2)
self.assertEqual(ix_info["hello_1"]["name"], "hello_1")
yield db.test.create_index(filter.sort(filter.DESCENDING("hello") +
filter.ASCENDING("world")),
unique=True, sparse=True)
ix_info = yield db.test.index_information()
self.assertEqual(ix_info["hello_1"]["name"], "hello_1")
self.assertEqual(len(ix_info), 3)
self.assertEqual({"hello": -1, "world": 1}, ix_info["hello_-1_world_1"]["key"])
self.assertEqual(True, ix_info["hello_-1_world_1"]["unique"])
self.assertEqual(True, ix_info["hello_-1_world_1"]["sparse"])
yield db.test.drop_indexes()
yield db.test.remove({})
示例2: __init__
def __init__(self, database, collection="fs"):
"""Create a new instance of :class:`GridFS`.
Raises :class:`TypeError` if `database` is not an instance of
:class:`~pymongo.database.Database`.
:Parameters:
- `database`: database to use
- `collection` (optional): root collection to use
.. note::
Instantiating a GridFS object will implicitly create it indexes.
This could leads to errors if the underlaying connection is closed
before the indexes creation request has returned. To avoid this you
should use the defer returned by :meth:`GridFS.indexes_created`.
.. versionadded:: 1.6
The `collection` parameter.
"""
if not isinstance(database, Database):
raise TypeError("TxMongo: database must be an instance of Database.")
self.__database = database
self.__collection = database[collection]
self.__files = self.__collection.files
self.__chunks = self.__collection.chunks
self.__indexes_created_defer = defer.DeferredList([
self.__files.create_index(
filter.sort(ASCENDING("filesname") + ASCENDING("uploadDate"))),
self.__chunks.create_index(
filter.sort(ASCENDING("files_id") + ASCENDING("n")), unique=True)
])
示例3: test_index_info
def test_index_info(self):
db = self.db
yield db.test.drop_indexes()
yield db.test.remove({})
db.test.save({}) # create collection
ix_info = yield db.test.index_information()
self.assertEqual(len(ix_info), 1)
self.assert_("_id_" in ix_info)
yield db.test.create_index(filter.sort(filter.ASCENDING("hello")))
ix_info = yield db.test.index_information()
self.assertEqual(len(ix_info), 2)
self.assertEqual(ix_info["hello_1"], [("hello", 1)])
yield db.test.create_index(filter.sort(filter.DESCENDING("hello") + filter.ASCENDING("world")), unique=True)
ix_info = yield db.test.index_information()
self.assertEqual(ix_info["hello_1"], [("hello", 1)])
self.assertEqual(len(ix_info), 3)
self.assertEqual([("world", 1), ("hello", -1)], ix_info["hello_-1_world_1"])
# Unique key will not show until index_information is updated with changes introduced in version 1.7
#self.assertEqual(True, ix_info["hello_-1_world_1"]["unique"])
yield db.test.drop_indexes()
yield db.test.remove({})
示例4: example
def example():
mongo = yield txmongo.MongoConnection()
foo = mongo.foo # `foo` database
test = foo.test # `test` collection
idx = filter.sort(filter.ASCENDING("something") + filter.DESCENDING("else"))
print "IDX:", idx
result = yield test.create_index(idx)
print "create_index:", result
result = yield test.index_information()
print "index_information:", result
result = yield test.drop_index(idx)
print "drop_index:", result
# Geohaystack example
geoh_idx = filter.sort(filter.GEOHAYSTACK("loc") + filter.ASCENDING("type"))
print "IDX:", geoh_idx
result = yield test.create_index(geoh_idx, **{'bucketSize':1})
print "index_information:", result
result = yield test.drop_index(geoh_idx)
print "drop_index:", result
# 2D geospatial index
geo_idx = filter.sort(filter.GEO2D("pos"))
print "IDX:", geo_idx
result = yield test.create_index(geo_idx, **{ 'min':-100, 'max':100 })
print "index_information:", result
result = yield test.drop_index(geo_idx)
print "drop_index:", result
示例5: get_last_version
def get_last_version(self, filename):
"""Get a file from GridFS by ``"filename"``.
Returns the most recently uploaded file in GridFS with the
name `filename` as an instance of
:class:`~gridfs.grid_file.GridOut`. Raises
:class:`~gridfs.errors.NoFile` if no such file exists.
An index on ``{filename: 1, uploadDate: -1}`` will
automatically be created when this method is called the first
time.
:Parameters:
- `filename`: ``"filename"`` of the file to get
.. versionadded:: 1.6
"""
self.__files.ensure_index(filter.sort(ASCENDING("filename") + DESCENDING("uploadDate")))
doc = yield self.__files.find_one({"filename": filename},
filter=filter.sort(DESCENDING("uploadDate")))
if doc is None:
raise NoFile("TxMongo: no file in gridfs with filename {0}".format(repr(filename)))
defer.returnValue(GridOut(self.__collection, doc))
示例6: test_Sort
def test_Sort(self):
doc = yield self.coll.find_one_and_delete({'x': {"$exists": True}},
sort=qf.sort(qf.ASCENDING('y')))
self.assertEqual(doc['x'], 1)
doc = yield self.coll.find_one_and_delete({'x': {"$exists": True}},
sort=qf.sort(qf.DESCENDING('y')))
self.assertEqual(doc['x'], 3)
cnt = yield self.coll.count()
self.assertEqual(cnt, 1)
示例7: test_FilterMerge
def test_FilterMerge(self):
self.assertEqual(qf.sort(qf.ASCENDING('x') + qf.DESCENDING('y')),
qf.sort(qf.ASCENDING('x')) + qf.sort(qf.DESCENDING('y')))
comment = "hello world"
yield self.db.command("profile", 2)
yield self.coll.find({}, filter=qf.sort(qf.ASCENDING('x')) + qf.comment(comment))
yield self.db.command("profile", 0)
cnt = yield self.db.system.profile.count({"query.$orderby.x": 1,
"query.$comment": comment})
self.assertEqual(cnt, 1)
示例8: test_Sort
def test_Sort(self):
doc = yield self.coll.find_one_and_replace({}, {'x': 5, 'y': 5},
projection={"_id": 0},
sort=qf.sort(qf.ASCENDING('y')))
self.assertEqual(doc, {'x': 10, 'y': 10})
doc = yield self.coll.find_one_and_replace({}, {'x': 40, 'y': 40},
projection={"_id": 0},
sort=qf.sort(qf.DESCENDING('y')))
self.assertEqual(doc, {'x': 30, 'y': 30})
ys = yield self.coll.distinct('y')
self.assertEqual(set(ys), set([5, 20, 40]))
示例9: test_index_haystack
def test_index_haystack(self):
db = self.db
coll = self.coll
yield coll.drop_indexes()
_id = yield coll.insert({
"pos": {"long": 34.2, "lat": 33.3},
"type": "restaurant"
})
yield coll.insert({
"pos": {"long": 34.2, "lat": 37.3}, "type": "restaurant"
})
yield coll.insert({
"pos": {"long": 59.1, "lat": 87.2}, "type": "office"
})
yield coll.create_index(filter.sort(filter.GEOHAYSTACK("pos") +
filter.ASCENDING("type")), **{"bucket_size": 1})
results = yield db.command("geoSearch", "mycol",
near=[33, 33],
maxDistance=6,
search={"type": "restaurant"},
limit=30)
self.assertEqual(2, len(results["results"]))
self.assertEqual({
"_id": _id,
"pos": {"long": 34.2, "lat": 33.3},
"type": "restaurant"
}, results["results"][0])
示例10: test_index_haystack
def test_index_haystack(self):
db = self.db
coll = self.coll
yield coll.drop_indexes()
_id = yield coll.insert({
"pos": {"long": 34.2, "lat": 33.3},
"type": "restaurant"
})
yield coll.insert({
"pos": {"long": 34.2, "lat": 37.3}, "type": "restaurant"
})
yield coll.insert({
"pos": {"long": 59.1, "lat": 87.2}, "type": "office"
})
yield coll.create_index(filter.sort(filter.GEOHAYSTACK("pos") + filter.ASCENDING("type")), **{'bucket_size': 1})
# TODO: A db.command method has not been implemented yet.
# Sending command directly
command = SON([
("geoSearch", "mycol"),
("near", [33, 33]),
("maxDistance", 6),
("search", {"type": "restaurant"}),
("limit", 30),
])
results = yield db["$cmd"].find_one(command)
self.assertEqual(2, len(results['results']))
self.assertEqual({
"_id": _id,
"pos": {"long": 34.2, "lat": 33.3},
"type": "restaurant"
}, results["results"][0])
示例11: process_message
def process_message(self, msg):
headers = 'headers' in msg.content.properties and \
msg.content.properties['headers'] or None
data = msg.content.body
log.msg('RECEIVED MSG: {}'.format(str(headers)))
log.msg(data)
part = {}
for key, value in self.run(data, headers):
ap = part.get(key, None)
if ap is None:
ap = []
part[key] = ap
ap.append((key, value))
data = dict(**headers)
data['result'] = json.dumps(part)
yield self.results.insert(SON(data))
# TODO: I think this is not right place for this code. @german
idx = filter.sort(filter.ASCENDING("task"))
self.results.ensure_index(idx)
headers['worker'] = 'map'
self.publisher.sendMessage('OK',
routing_key=ns.MASTER_QUEUE,
headers=headers)
returnValue(msg)
示例12: test_index_text
def test_index_text(self):
ix = yield self.coll.create_index(qf.sort(qf.TEXT("title") + qf.TEXT("summary")),
weights={"title": 100, "summary": 20})
self.assertEqual("title_text_summary_text", ix)
index_info = yield self.coll.index_information()
self.assertEqual(index_info[ix]["key"], {"_fts": "text", "_ftsx": 1})
self.assertEqual(index_info[ix]["weights"], {"title": 100, "summary": 20})
示例13: evaluateIndex
def evaluateIndex(self, indxs):
if ('EmailIndex' in indxs) and (indxs['EmailIndex']['unique'] == True):
return
else:
logging.info("Creating email index...")
self.collection.create_index(
qf.sort(qf.ASCENDING('Email')),
name="EmailIndex", unique=True)
示例14: test_Failures
def test_Failures(self):
# can't alter _id
yield self.assertFailure(self.coll.update_many({}, {"$set": {"_id": 1}}), WriteError)
# invalid field name
yield self.assertFailure(self.coll.update_many({}, {"$set": {'$': 1}}), WriteError)
yield self.coll.create_index(qf.sort(qf.ASCENDING('x')), unique=True)
yield self.assertFailure(self.coll.update_many({'x': 2}, {"$set": {'x': 1}}), DuplicateKeyError)
示例15: test_create_index_nodup
def test_create_index_nodup(self):
coll = self.coll
yield coll.insert({"b": 1})
yield coll.insert({"b": 1})
ix = coll.create_index(qf.sort(qf.ASCENDING("b")), unique=True)
yield self.assertFailure(ix, errors.DuplicateKeyError)