• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python filter.sort函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中txmongo.filter.sort函数的典型用法代码示例。如果您正苦于以下问题:Python sort函数的具体用法?Python sort怎么用?Python sort使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了sort函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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({})
开发者ID:rafallo,项目名称:txmongo,代码行数:28,代码来源:test_collection.py


示例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)
        ])
开发者ID:dynamikdev,项目名称:txmongo,代码行数:33,代码来源:__init__.py


示例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({})
开发者ID:claytondaley,项目名称:mongo-async-python-driver,代码行数:29,代码来源:test_collection.py


示例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
开发者ID:amferraz,项目名称:mongo-async-python-driver,代码行数:35,代码来源:index.py


示例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))
开发者ID:dynamikdev,项目名称:txmongo,代码行数:25,代码来源:__init__.py


示例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)
开发者ID:deconevidya,项目名称:txmongo,代码行数:11,代码来源:test_queries.py


示例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)
开发者ID:DxCx,项目名称:txmongo,代码行数:13,代码来源:test_filters.py


示例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]))
开发者ID:gaochunzy,项目名称:txmongo,代码行数:13,代码来源:test_queries.py


示例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])
开发者ID:rafallo,项目名称:txmongo,代码行数:30,代码来源:test_collection.py


示例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])
开发者ID:claytondaley,项目名称:mongo-async-python-driver,代码行数:35,代码来源:test_collection.py


示例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)
开发者ID:yunmanger1,项目名称:task-mapreduce,代码行数:29,代码来源:worker_map.py


示例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})
开发者ID:tonal,项目名称:txmongo,代码行数:8,代码来源:test_collection.py


示例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)
开发者ID:chamilto,项目名称:tnscraper,代码行数:8,代码来源:pipelines.py


示例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)
开发者ID:jianleon,项目名称:txmongo,代码行数:8,代码来源:test_queries.py


示例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)
开发者ID:twisted,项目名称:txmongo,代码行数:8,代码来源:test_collection.py


示例16: test_index_geo2d

    def test_index_geo2d(self):
        coll = self.coll
        geo_ix = yield coll.create_index(qf.sort(qf.GEO2D("loc")))

        self.assertEqual("loc_2d", geo_ix)

        index_info = yield coll.index_information()
        self.assertEqual({"loc": "2d"}, index_info["loc_2d"]["key"])
开发者ID:twisted,项目名称:txmongo,代码行数:8,代码来源:test_collection.py


示例17: test_index_geo2dsphere

    def test_index_geo2dsphere(self):
        coll = self.coll
        geo_ix = yield coll.create_index(qf.sort(qf.GEO2DSPHERE("loc")))

        self.assertEqual("loc_2dsphere", geo_ix)
        index_info = yield coll.index_information()

        self.assertEqual(index_info["loc_2dsphere"]["key"], {"loc": "2dsphere"})
开发者ID:twisted,项目名称:txmongo,代码行数:8,代码来源:test_collection.py


示例18: render_GET

 def render_GET(self, request):
     def handle_posts(posts):
         context = {'posts': posts}
         request.write(render_response('posts.html', context))
         request.finish()
     f = _filter.sort(_filter.DESCENDING('date'))
     deferred = _db.posts.find(filter=f)
     deferred.addCallback(handle_posts)
     return NOT_DONE_YET
开发者ID:MATTALUI,项目名称:AtlasThunder,代码行数:9,代码来源:resources.py


示例19: ensure_indexes

 def ensure_indexes(cls):
     """
     Check&create if needed the Document's indexes in database
     """
     for index in cls.opts.indexes:
         kwargs = index.document.copy()
         keys = kwargs.pop('key')
         index = qf.sort([(k, d) for k, d in keys.items()])
         yield cls.collection.create_index(index, **kwargs)
开发者ID:Nobatek,项目名称:umongo,代码行数:9,代码来源:txmongo.py


示例20: test_create_index_nodup

    def test_create_index_nodup(self):
        coll = self.coll

        ret = yield coll.drop()
        ret = yield coll.insert({'b': 1})
        ret = yield coll.insert({'b': 1})

        ix = coll.create_index(filter.sort(filter.ASCENDING("b")), unique=True)
        yield self.assertFailure(ix, errors.DuplicateKeyError)
开发者ID:claytondaley,项目名称:mongo-async-python-driver,代码行数:9,代码来源:test_collection.py



注:本文中的txmongo.filter.sort函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python rdq.ResizableDispatchQueue类代码示例发布时间:2022-05-27
下一篇:
Python utils.now函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap