zope目录的多字段索引
z3c.multifieldindex的Python项目详细描述
z3c.多字段索引
这个包为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
让我们创建一组Person对象:
>>> 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”方法应返回一个iterable of(name,field)对字段 应该编入索引。将为这些字段创建子索引。
“_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,文本索引工厂创建 佐佩。索引的文本索引。这需要知道何时进行查询。
好的,现在让我们创建一个index实例并准备使用它。
>>> index = PersonIndex() >>> index.recreateIndexes()
“重新创建索引”会重新创建子索引。它通常被称为 由这个包提供的iobjectaddedevent的订户提供,但是我们只是 这次考试用手打电话。
现在,让我们为person对象建立索引:
>>> 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(2009年10月15日)
- 初始版本(使用Zope3.4依赖项)。