Skip to content

Commit

Permalink
Add sorting support from zope.index's FieldIndex.
Browse files Browse the repository at this point in the history
  • Loading branch information
nadako committed Feb 27, 2009
1 parent 03dda5f commit 06082c2
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 3 deletions.
2 changes: 1 addition & 1 deletion CHANGES.txt
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Zope 3.3/ZODB 3.7.
1.4.1 (unreleased)
------------------

*
* Add FieldIndex-like sorting support for the ValueIndex.


1.4.0 (2009-02-07)
Expand Down
2 changes: 1 addition & 1 deletion buildout.cfg
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[buildout]
develop = .
develop = . ../zope.index
parts = test

[test]
Expand Down
8 changes: 7 additions & 1 deletion src/zc/catalog/index.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import zope.component.interfaces
import zope.interface.common.idatetime
import zope.index.interfaces
from zope.index.field.sorting import SortingIndexMixin
import zope.security.management
from zope.publisher.interfaces import IRequest
import zc.catalog.interfaces
Expand Down Expand Up @@ -150,10 +151,15 @@ def parseQuery(query):
raise ValueError('may only pass a dict to apply')
return query_type, query

class ValueIndex(AbstractIndex):
class ValueIndex(SortingIndexMixin, AbstractIndex):

interface.implements(zc.catalog.interfaces.IValueIndex)

# attributes used by sorting mixin
_sorting_num_docs_attr = 'documentCount' # Length object
_sorting_fwd_index_attr = 'values_to_documents' # forward BTree index
_sorting_rev_index_attr = 'documents_to_values' # reverse BTree index

def _add_value(self, doc_id, added):
values_to_documents = self.values_to_documents
docs = values_to_documents.get(added)
Expand Down
37 changes: 37 additions & 0 deletions src/zc/catalog/valueindex.txt
Original file line number Diff line number Diff line change
Expand Up @@ -220,3 +220,40 @@ values.
True
>>> index.containsValue('q')
False

Sorting
-------

Value indexes supports sorting, just like zope.index.field.FieldIndex.

>>> index.clear()

>>> index.index_doc(1, 9)
>>> index.index_doc(2, 8)
>>> index.index_doc(3, 7)
>>> index.index_doc(4, 6)
>>> index.index_doc(5, 5)
>>> index.index_doc(6, 4)
>>> index.index_doc(7, 3)
>>> index.index_doc(8, 2)
>>> index.index_doc(9, 1)

>>> list(index.sort([4, 2, 9, 7, 3, 1, 5]))
[9, 7, 5, 4, 3, 2, 1]

We can also specify the ``reverse`` argument to reverse results:

>>> list(index.sort([4, 2, 9, 7, 3, 1, 5], reverse=True))
[1, 2, 3, 4, 5, 7, 9]

And as per IIndexSort, we can limit results by specifying the ``limit``
argument:

>>> list(index.sort([4, 2, 9, 7, 3, 1, 5], limit=3))
[9, 7, 5]

If we pass an id that is not indexed by this index, it won't be included
in the result.

>>> list(index.sort([2, 10]))
[2]

0 comments on commit 06082c2

Please sign in to comment.