zope目录的多字段索引
项目描述
z3c.multifieldindex
本软件包为zope目录提供了一个索引,可以索引多个字段。当字段集动态时(例如具有可定制的持久字段),它很有用。
实际上,本软件包提供了一个自定义多字段索引的基类,并要使其工作,您需要覆盖其中的一些方法。但是,首先,让我们创建一个我们将要使用的内容模式和使用接口
>>> from zope.interface import Interface, implements >>> from zope.schema import Text, Int, List, TextLine>>> class IPerson(Interface): ... ... age = Int() ... info = Text() ... skills = List(value_type=TextLine())>>> class Person(object): ... ... implements(IPerson) ... ... def __init__(self, age, info, skills): ... self.age = age ... self.info = info ... self.skills = skills
让我们创建一组人员对象
>>> dataset = [ ... (1, Person(20, u'Sweet and cute', ['dancing', 'singing'])), ... (2, Person(33, u'Smart and sweet', ['math', 'dancing'])), ... (3, Person(6, u'Young and cute', ['singing', 'painting'])), ... ]
我们选择了这些不同类型的字段来展示索引足够智能,知道如何索引每种类型的值。我们将在本文档的后面回到这个话题。
现在,我们需要创建一个多字段索引类,用于索引我们的人员对象。我们将覆盖其中的两个方法来使其具有功能
>>> from z3c.multifieldindex.index import MultiFieldIndexBase >>> from zope.schema import getFields>>> class PersonIndex(MultiFieldIndexBase): ... ... def _fields(self): ... return getFields(IPerson).items() ... ... def _getData(self, object): ... return { ... 'age': object.age, ... 'info': object.info, ... 'skills': object.skills, ... }
“_fields”方法应返回一个字段对(名称,字段)的可迭代对象,这些字段应被索引。将为这些字段创建子索引。
“_getData”方法返回一个字典,其中包含使用给定对象要索引的数据。字典的键应匹配字段名称。
子索引通过为每个字段查找索引工厂自动创建。本软件包提供了三个最常用的工厂。让我们将它们注册以继续(这也在本软件包的configure.zcml文件中完成)
>>> from z3c.multifieldindex.subindex import DefaultIndexFactory >>> from z3c.multifieldindex.subindex import CollectionIndexFactory >>> from z3c.multifieldindex.subindex import TextIndexFactory >>> from zope.component import provideAdapter>>> provideAdapter(DefaultIndexFactory) >>> provideAdapter(CollectionIndexFactory) >>> provideAdapter(TextIndexFactory)
默认索引工厂创建zc.catalog的ValueIndex,集合索引工厂创建zc.catalog的SetIndex,文本索引工厂创建zope.index的TextIndex。这在执行查询时是必要的。
好的,现在让我们创建索引的一个实例并准备使用。
>>> index = PersonIndex() >>> index.recreateIndexes()
“recreateIndexes”方法重新创建子索引。它通常由本软件包提供的IObjectAddedEvent的订阅者调用,但我们简单地手动调用它以进行测试。
现在,让我们最终索引我们的人员对象
>>> for docid, person in dataset: ... index.index_doc(docid, person)
现在让我们进行一次查询。查询格式非常简单。它是一个字典,其中键是字段名称,值是对子索引的查询。
>>> results = index.apply({ ... 'skills': {'any_of': ('singing', 'painting')}, ... }) >>> list(results) [1, 3]>>> results = index.apply({ ... 'info': 'sweet', ... }) >>> list(results) [1, 2]>>> results = index.apply({ ... 'age': {'between': (1, 30)}, ... }) >>> list(results) [1, 3]>>> results = index.apply({ ... 'age': {'between': (1, 30)}, ... 'skills': {'any_of': ('dancing', )}, ... }) >>> list(results) [1]
变更
3.4.0 (15-10-2009)
初始版本(使用 Zope 3.4 依赖项)。
项目详情
关闭
z3c.multifieldindex-3.4.0.tar.gz 的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | 6408592f2ccdc8b94b09a7bc601332dfd5e7f15ece437d377a85f406ea835103 |
|
MD5 | 33ba724ad25ffded2543ba6ee80c9552 |
|
BLAKE2b-256 | 2abbce571e83cb4a4f1092560a4d641ab3819177540031df473c3789e7e18223 |