Skip to main content

Index intransitive and transitive n-ary relationships.

Project description

Relation Catalog

Overview

The relation catalog can be used to optimize intransitive and transitive searches for N-ary relations of finite, preset dimensions.

For example, you can index simple two-way relations, like employee to supervisor; RDF-style triples of subject-predicate-object; and more complex relations such as subject-predicate-object with context and state. These can be searched with variable definitions of transitive behavior.

The catalog can be used in the ZODB or standalone. It is a generic, relatively policy-free tool.

It is expected to be used usually as an engine for more specialized and constrained tools and APIs. Three such tools are zc.relationship containers, plone.relations containers, and zc.vault. The documents in the package, including this one, describe other possible uses.

History

This is a refactoring of the ZODB-only parts of the zc.relationship package. Specifically, the zc.relation catalog is largely equivalent to the zc.relationship index. The index in the zc.relationship 2.x line is an almost-completely backwards-compatible wrapper of the zc.relation catalog. zc.relationship will continue to be maintained, though active development is expected to go into zc.relation.

Many of the ideas come from discussions with and code from Casey Duncan, Tres Seaver, Ken Manheimer, and more.

Setting Up a Relation Catalog

In this section, we will be introducing the following ideas.

  • Relations are objects with indexed values.

  • You add value indexes to relation catalogs to be able to search. Values can be identified to the catalog with callables or interface elements. The indexed value must be specified to the catalog as a single value or a collection.

  • Relations and their values are stored in the catalog as tokens: unique identifiers that you can resolve back to the original value. Integers are the most efficient tokens, but others can work fine too.

  • Token type determines the BTree module needed.

  • You must define your own functions for tokenizing and resolving tokens. These functions are registered with the catalog for the relations and for each of their value indexes.

  • Relations are indexed with index.

We will use a simple two way relation as our example here. A brief introduction to a more complex RDF-style subject-predicate-object set up can be found later in the document.

Creating the Catalog

Imagine a two way relation from one value to another. Let’s say that we are modeling a relation of people to their supervisors: an employee may have a single supervisor. For this first example, the relation between employee and supervisor will be intrinsic: the employee has a pointer to the supervisor, and the employee object itself represents the relation.

Let’s say further, for simplicity, that employee names are unique and can be used to represent employees. We can use names as our “tokens”.

Tokens are similar to the primary key in a relational database. A token is a way to identify an object. It must sort reliably and you must be able to write a callable that reliably resolves to the object given the right context. In Zope 3, intids (zope.app.intid) and keyreferences (zope.app.keyreference) are good examples of reasonable tokens.

As we’ll see below, you provide a way to convert objects to tokens, and resolve tokens to objects, for the relations, and for each value index individually. They can be the all the same functions or completely different, depending on your needs.

For speed, integers make the best tokens; followed by other immutables like strings; followed by non-persistent objects; followed by persistent objects. The choice also determines a choice of BTree module, as we’ll see below.

Here is our toy Employee example class. Again, we will use the employee name as the tokens.

>>> employees = {} # we'll use this to resolve the "name" tokens
>>> from functools import total_ordering
>>> @total_ordering
... class Employee(object):
...     def __init__(self, name, supervisor=None):
...         if name in employees:
...             raise ValueError('employee with same name already exists')
...         self.name = name # expect this to be readonly
...         self.supervisor = supervisor
...         employees[name] = self
...     # the next parts just make the tests prettier
...     def __repr__(self):
...         return '<Employee instance "' + self.name + '">'
...     def __lt__(self, other):
...         return self.name < other.name
...     def __eq__(self, other):
...         return self is other
...     def __hash__(self):
...         ''' Dummy method needed because we defined __eq__
...         '''
...         return 1
...

So, we need to define how to turn employees into their tokens. We call the tokenization a “dump” function. Conversely, the function to resolve tokens into objects is called a “load”.

Functions to dump relations and values get several arguments. The first argument is the object to be tokenized. Next, because it helps sometimes to provide context, is the catalog. The last argument is a dictionary that will be shared for a given search. The dictionary can be ignored, or used as a cache for optimizations (for instance, to stash a utility that you looked up).

For this example, our function is trivial: we said the token would be the employee’s name.

>>> def dumpEmployees(emp, catalog, cache):
...     return emp.name
...

If you store the relation catalog persistently (e.g., in the ZODB) be aware that the callables you provide must be picklable–a module-level function, for instance.

We also need a way to turn tokens into employees, or “load”.

The “load” functions get the token to be resolved; the catalog, for context; and a dict cache, for optimizations of subsequent calls.

You might have noticed in our Employee.__init__ that we keep a mapping of name to object in the employees global dict (defined right above the class definition). We’ll use that for resolving the tokens.

>>> def loadEmployees(token, catalog, cache):
...     return employees[token]
...

Now we know enough to get started with a catalog. We’ll instantiate it by specifying how to tokenize relations, and what kind of BTree modules should be used to hold the tokens.

How do you pick BTree modules?

  • If the tokens are 32-bit ints, choose BTrees.family32.II, BTrees.family32.IF or BTrees.family32.IO.

  • If the tokens are 64 bit ints, choose BTrees.family64.II, BTrees.family64.IF or BTrees.family64.IO.

  • If they are anything else, choose BTrees.family32.OI, BTrees.family64.OI, or BTrees.family32.OO (or BTrees.family64.OO–they are the same).

Within these rules, the choice is somewhat arbitrary unless you plan to merge these results with that of another source that is using a particular BTree module. BTree set operations only work within the same module, so you must match module to module. The catalog defaults to IF trees, because that’s what standard zope catalogs use. That’s as reasonable a choice as any, and will potentially come in handy if your tokens are in fact the same as those used by the zope catalog and you want to do some set operations.

In this example, our tokens are strings, so we want OO or an OI variant. We’ll choose BTrees.family32.OI, arbitrarily.

>>> import zc.relation.catalog
>>> import BTrees
>>> catalog = zc.relation.catalog.Catalog(dumpEmployees, loadEmployees,
...                                       btree=BTrees.family32.OI)

[1]

[2]

Look! A relation catalog! We can’t do very much searching with it so far though, because the catalog doesn’t have any indexes.

In this example, the relation itself represents the employee, so we won’t need to index that separately.

But we do need a way to tell the catalog how to find the other end of the relation, the supervisor. You can specify this to the catalog with an attribute or method specified from zope.interface Interface, or with a callable. We’ll use a callable for now. The callable will receive the indexed relation and the catalog for context.

>>> def supervisor(emp, catalog):
...     return emp.supervisor # None or another employee
...

We’ll also need to specify how to tokenize (dump and load) those values. In this case, we’re able to use the same functions as the relations themselves. However, do note that we can specify a completely different way to dump and load for each “value index,” or relation element.

We could also specify the name to call the index, but it will default to the __name__ of the function (or interface element), which will work just fine for us now.

Now we can add the “supervisor” value index.

>>> catalog.addValueIndex(supervisor, dumpEmployees, loadEmployees,
...                       btree=BTrees.family32.OI)

Now we have an index [3].

Adding Relations

Now let’s create a few employees. All but one will have supervisors. If you recall our toy Employee class, the first argument to the constructor is the employee name (and therefore the token), and the optional second argument is the supervisor.

>>> a = Employee('Alice')
>>> b = Employee('Betty', a)
>>> c = Employee('Chuck', a)
>>> d = Employee('Diane', b)
>>> e = Employee('Edgar', b)
>>> f = Employee('Frank', c)
>>> g = Employee('Galyn', c)
>>> h = Employee('Howie', d)

Here is a diagram of the hierarchy.

            Alice
         __/     \__
    Betty           Chuck
    /   \           /   \
Diane   Edgar   Frank   Galyn
  |
Howie

Let’s tell the catalog about the relations, using the index method.

>>> for emp in (a,b,c,d,e,f,g,h):
...     catalog.index(emp)
...

We’ve now created the relation catalog and added relations to it. We’re ready to search!

Searching

In this section, we will introduce the following ideas.

  • Queries to the relation catalog are formed with dicts.

  • Query keys are the names of the indexes you want to search, or, for the special case of precise relations, the zc.relation.RELATION constant.

  • Query values are the tokens of the results you want to match; or None, indicating relations that have None as a value (or an empty collection, if it is a multiple). Search values can use zc.relation.catalog.any(args) or zc.relation.catalog.Any(args) to specify multiple (non-None) results to match for a given key.

  • The index has a variety of methods to help you work with tokens. tokenizeQuery is typically the most used, though others are available.

  • To find relations that match a query, use findRelations or findRelationTokens.

  • To find values that match a query, use findValues or findValueTokens.

  • You search transitively by using a query factory. The zc.relation.queryfactory.TransposingTransitive is a good common case factory that lets you walk up and down a hierarchy. A query factory can be passed in as an argument to search methods as a queryFactory, or installed as a default behavior using addDefaultQueryFactory.

  • To find how a query is related, use findRelationChains or findRelationTokenChains.

  • To find out if a query is related, use canFind.

  • Circular transitive relations are handled to prevent infinite loops. They are identified in findRelationChains and findRelationTokenChains with a zc.relation.interfaces.ICircularRelationPath marker interface.

  • search methods share the following arguments:

    • maxDepth, limiting the transitive depth for searches;

    • filter, allowing code to filter transitive paths;

    • targetQuery, allowing a query to filter transitive paths on the basis of the endpoint;

    • targetFilter, allowing code to filter transitive paths on the basis of the endpoint; and

    • queryFactory, mentioned above.

  • You can set up search indexes to speed up specific transitive searches.

Queries, findRelations, and special query values

So who works for Alice? That means we want to get the relations–the employees–with a supervisor of Alice.

The heart of a question to the catalog is a query. A query is spelled as a dictionary. The main idea is simply that keys in a dictionary specify index names, and the values specify the constraints.

The values in a query are always expressed with tokens. The catalog has several helpers to make this less onerous, but for now let’s take advantage of the fact that our tokens are easily comprehensible.

>>> sorted(catalog.findRelations({'supervisor': 'Alice'}))
[<Employee instance "Betty">, <Employee instance "Chuck">]

Alice is the direct (intransitive) boss of Betty and Chuck.

What if you want to ask “who doesn’t report to anyone?” Then you want to ask for a relation in which the supervisor is None.

>>> list(catalog.findRelations({'supervisor': None}))
[<Employee instance "Alice">]

Alice is the only employee who doesn’t report to anyone.

What if you want to ask “who reports to Diane or Chuck?” Then you use the zc.relation Any class or any function to pass the multiple values.

>>> sorted(catalog.findRelations(
...     {'supervisor': zc.relation.catalog.any('Diane', 'Chuck')}))
... # doctest: +NORMALIZE_WHITESPACE
[<Employee instance "Frank">, <Employee instance "Galyn">,
 <Employee instance "Howie">]

Frank, Galyn, and Howie each report to either Diane or Chuck. [4]

findValues and the RELATION query key

So how do we find who an employee’s supervisor is? Well, in this case, look at the attribute on the employee! If you can use an attribute that will usually be a win in the ZODB.

>>> h.supervisor
<Employee instance "Diane">

Again, as we mentioned at the start of this first example, the knowledge of a supervisor is “intrinsic” to the employee instance. It is possible, and even easy, to ask the catalog this kind of question, but the catalog syntax is more geared to “extrinsic” relations, such as the one from the supervisor to the employee: the connection between a supervisor object and its employees is extrinsic to the supervisor, so you actually might want a catalog to find it!

However, we will explore the syntax very briefly, because it introduces an important pair of search methods, and because it is a stepping stone to our first transitive search.

So, o relation catalog, who is Howie’s supervisor?

To ask this question we want to get the indexed values off of the relations: findValues. In its simplest form, the arguments are the index name of the values you want, and a query to find the relations that have the desired values.

What about the query? Above, we noted that the keys in a query are the names of the indexes to search. However, in this case, we don’t want to search one or more indexes for matching relations, as usual, but actually specify a relation: Howie.

We do not have a value index name: we are looking for a relation. The query key, then, should be the constant zc.relation.RELATION. For our current example, that would mean the query is {zc.relation.RELATION: 'Howie'}.

>>> import zc.relation
>>> list(catalog.findValues(
...     'supervisor', {zc.relation.RELATION: 'Howie'}))[0]
<Employee instance "Diane">

Congratulations, you just found an obfuscated and comparitively inefficient way to write howie.supervisor! [5]

[6]

Slightly more usefully, you can use other query keys along with zc.relation.RELATION. This asks, “Of Betty, Alice, and Frank, who are supervised by Alice?”

>>> sorted(catalog.findRelations(
...     {zc.relation.RELATION: zc.relation.catalog.any(
...         'Betty', 'Alice', 'Frank'),
...      'supervisor': 'Alice'}))
[<Employee instance "Betty">]

Only Betty is.

Tokens

As mentioned above, the catalog provides several helpers to work with tokens. The most frequently used is tokenizeQuery, which takes a query with object values and converts them to tokens using the “dump” functions registered for the relations and indexed values. Here are alternate spellings of some of the queries we’ve encountered above.

>>> catalog.tokenizeQuery({'supervisor': a})
{'supervisor': 'Alice'}
>>> catalog.tokenizeQuery({'supervisor': None})
{'supervisor': None}
>>> import pprint
>>> result = catalog.tokenizeQuery(
...     {zc.relation.RELATION: zc.relation.catalog.any(a, b, f),
...     'supervisor': a}) # doctest: +NORMALIZE_WHITESPACE
>>> pprint.pprint(result)
{None: <zc.relation.catalog.Any instance ('Alice', 'Betty', 'Frank')>,
 'supervisor': 'Alice'}

(If you are wondering about that None in the last result, yes, zc.relation.RELATION is just readability sugar for None.)

So, here’s a real search using tokenizeQuery. We’ll make an alias for catalog.tokenizeQuery just to shorten things up a bit.

>>> query = catalog.tokenizeQuery
>>> sorted(catalog.findRelations(query(
...     {zc.relation.RELATION: zc.relation.catalog.any(a, b, f),
...      'supervisor': a})))
[<Employee instance "Betty">]

The catalog always has parallel search methods, one for finding objects, as seen above, and one for finding tokens (the only exception is canFind, described below). Finding tokens can be much more efficient, especially if the result from the relation catalog is just one step along the path of finding your desired result. But finding objects is simpler for some common cases. Here’s a quick example of some queries above, getting tokens rather than objects.

You can also spell a query in tokenizeQuery with keyword arguments. This won’t work if your key is zc.relation.RELATION, but otherwise it can improve readability. We’ll see some examples of this below as well.

>>> sorted(catalog.findRelationTokens(query(supervisor=a)))
['Betty', 'Chuck']
>>> sorted(catalog.findRelationTokens({'supervisor': None}))
['Alice']
>>> sorted(catalog.findRelationTokens(
...     query(supervisor=zc.relation.catalog.any(c, d))))
['Frank', 'Galyn', 'Howie']
>>> sorted(catalog.findRelationTokens(
...     query({zc.relation.RELATION: zc.relation.catalog.any(a, b, f),
...            'supervisor': a})))
['Betty']

The catalog provides several other methods just for working with tokens.

  • resolveQuery: the inverse of tokenizeQuery, converting a tokenizedquery to a query with objects.

  • tokenizeValues: returns an iterable of tokens for the values of the given index name.

  • resolveValueTokens: returns an iterable of values for the tokens of the given index name.

  • tokenizeRelation: returns a token for the given relation.

  • resolveRelationToken: returns a relation for the given token.

  • tokenizeRelations: returns an iterable of tokens for the relations given.

  • resolveRelationTokens: returns an iterable of relations for the tokens given.

These methods are lesser used, and described in more technical documents in this package.

Transitive Searching, Query Factories, and maxDepth

So, we’ve seen a lot of one-level, intransitive searching. What about transitive searching? Well, you need to tell the catalog how to walk the tree. In simple (and very common) cases like this, the zc.relation.queryfactory.TransposingTransitive will do the trick.

A transitive query factory is just a callable that the catalog uses to ask “I got this query, and here are the results I found. I’m supposed to walk another step transitively, so what query should I search for next?” Writing a factory is more complex than we want to talk about right now, but using the TransposingTransitiveQueryFactory is easy. You just tell it the two query names it should transpose for walking in either direction.

For instance, here we just want to tell the factory to transpose the two keys we’ve used, zc.relation.RELATION and ‘supervisor’. Let’s make a factory, use it in a query for a couple of transitive searches, and then, if you want, you can read through a footnote to talk through what is happening.

Here’s the factory.

>>> import zc.relation.queryfactory
>>> factory = zc.relation.queryfactory.TransposingTransitive(
...     zc.relation.RELATION, 'supervisor')

Now factory is just a callable. Let’s let it help answer a couple of questions.

Who are all of Howie’s supervisors transitively (this looks up in the diagram)?

>>> list(catalog.findValues('supervisor', {zc.relation.RELATION: 'Howie'},
...      queryFactory=factory))
... # doctest: +NORMALIZE_WHITESPACE
[<Employee instance "Diane">, <Employee instance "Betty">,
 <Employee instance "Alice">]

Who are all of the people Betty supervises transitively, breadth first (this looks down in the diagram)?

>>> people = list(catalog.findRelations(
...     {'supervisor': 'Betty'}, queryFactory=factory))
>>> sorted(people[:2])
[<Employee instance "Diane">, <Employee instance "Edgar">]
>>> people[2]
<Employee instance "Howie">

Yup, that looks right. So how did that work? If you care, read this footnote. [13]

This transitive factory is really the only transitive factory you would want for this particular catalog, so it probably is safe to wire it in as a default. You can add multiple query factories to match different queries using addDefaultQueryFactory.

>>> catalog.addDefaultQueryFactory(factory)

Now all searches are transitive by default.

>>> list(catalog.findValues('supervisor', {zc.relation.RELATION: 'Howie'}))
... # doctest: +NORMALIZE_WHITESPACE
[<Employee instance "Diane">, <Employee instance "Betty">,
 <Employee instance "Alice">]
>>> people = list(catalog.findRelations({'supervisor': 'Betty'}))
>>> sorted(people[:2])
[<Employee instance "Diane">, <Employee instance "Edgar">]
>>> people[2]
<Employee instance "Howie">

We can force a non-transitive search, or a specific search depth, with maxDepth [7].

[8]

We’ll introduce some other available search arguments later in this document and in other documents. It’s important to note that all search methods share the same arguments as ``findRelations``. findValues and findValueTokens only add the initial argument of specifying the desired value.

We’ve looked at two search methods so far: the findValues and findRelations methods help you ask what is related. But what if you want to know how things are transitively related?

findRelationChains and targetQuery

Another search method, findRelationChains, helps you discover how things are transitively related.

The method name says “find relation chains”. But what is a “relation chain”? In this API, it is a transitive path of relations. For instance, what’s the chain of command above Howie? findRelationChains will return each unique path.

>>> list(catalog.findRelationChains({zc.relation.RELATION: 'Howie'}))
... # doctest: +NORMALIZE_WHITESPACE
[(<Employee instance "Howie">,),
 (<Employee instance "Howie">, <Employee instance "Diane">),
 (<Employee instance "Howie">, <Employee instance "Diane">,
  <Employee instance "Betty">),
 (<Employee instance "Howie">, <Employee instance "Diane">,
 <Employee instance "Betty">, <Employee instance "Alice">)]

Look at that result carefully. Notice that the result is an iterable of tuples. Each tuple is a unique chain, which may be a part of a subsequent chain. In this case, the last chain is the longest and the most comprehensive.

What if we wanted to see all the paths from Alice? That will be one chain for each supervised employee, because it shows all possible paths.

>>> sorted(catalog.findRelationChains(
...     {'supervisor': 'Alice'}))
... # doctest: +NORMALIZE_WHITESPACE
[(<Employee instance "Betty">,),
 (<Employee instance "Betty">, <Employee instance "Diane">),
 (<Employee instance "Betty">, <Employee instance "Diane">,
  <Employee instance "Howie">),
 (<Employee instance "Betty">, <Employee instance "Edgar">),
 (<Employee instance "Chuck">,),
 (<Employee instance "Chuck">, <Employee instance "Frank">),
 (<Employee instance "Chuck">, <Employee instance "Galyn">)]

That’s all the paths–all the chains–from Alice. We sorted the results, but normally they would be breadth first.

But what if we wanted to just find the paths from one query result to another query result–say, we wanted to know the chain of command from Alice down to Howie? Then we can specify a targetQuery that specifies the characteristics of our desired end point (or points).

>>> list(catalog.findRelationChains(
...     {'supervisor': 'Alice'},
...     targetQuery={zc.relation.RELATION: 'Howie'}))
... # doctest: +NORMALIZE_WHITESPACE
[(<Employee instance "Betty">, <Employee instance "Diane">,
  <Employee instance "Howie">)]

So, Betty supervises Diane, who supervises Howie.

Note that targetQuery now joins maxDepth in our collection of shared search arguments that we have introduced.

filter and targetFilter

We can take a quick look now at the last of the two shared search arguments: filter and targetFilter. These two are similar in that they both are callables that can approve or reject given relations in a search based on whatever logic you can code. They differ in that filter stops any further transitive searches from the relation, while targetFilter merely omits the given result but allows further search from it. Like targetQuery, then, targetFilter is good when you want to specify the other end of a path.

As an example, let’s say we only want to return female employees.

>>> female_employees = ('Alice', 'Betty', 'Diane', 'Galyn')
>>> def female_filter(relchain, query, catalog, cache):
...     return relchain[-1] in female_employees
...

Here are all the female employees supervised by Alice transitively, using targetFilter.

>>> list(catalog.findRelations({'supervisor': 'Alice'},
...                            targetFilter=female_filter))
... # doctest: +NORMALIZE_WHITESPACE
[<Employee instance "Betty">, <Employee instance "Diane">,
 <Employee instance "Galyn">]

Here are all the female employees supervised by Chuck.

>>> list(catalog.findRelations({'supervisor': 'Chuck'},
...                            targetFilter=female_filter))
[<Employee instance "Galyn">]

The same method used as a filter will only return females directly supervised by other females–not Galyn, in this case.

>>> list(catalog.findRelations({'supervisor': 'Alice'},
...                            filter=female_filter))
[<Employee instance "Betty">, <Employee instance "Diane">]

These can be combined with one another, and with the other search arguments [9].

Search indexes

Without setting up any additional indexes, the transitive behavior of the findRelations and findValues methods essentially relies on the brute force searches of findRelationChains. Results are iterables that are gradually computed. For instance, let’s repeat the question “Whom does Betty supervise?”. Notice that res first populates a list with three members, but then does not populate a second list. The iterator has been exhausted.

>>> res = catalog.findRelationTokens({'supervisor': 'Betty'})
>>> unindexed = sorted(res)
>>> len(unindexed)
3
>>> len(list(res)) # iterator is exhausted
0

The brute force of this approach can be sufficient in many cases, but sometimes speed for these searches is critical. In these cases, you can add a “search index”. A search index speeds up the result of one or more precise searches by indexing the results. Search indexes can affect the results of searches with a queryFactory in findRelations, findValues, and the soon-to-be-introduced canFind, but they do not affect findRelationChains.

The zc.relation package currently includes two kinds of search indexes, one for indexing transitive membership searches in a hierarchy and one for intransitive searches explored in tokens.rst in this package, which can optimize frequent searches on complex queries or can effectively change the meaning of an intransitive search. Other search index implementations and approaches may be added in the future.

Here’s a very brief example of adding a search index for the transitive searches seen above that specify a ‘supervisor’.

>>> import zc.relation.searchindex
>>> catalog.addSearchIndex(
...     zc.relation.searchindex.TransposingTransitiveMembership(
...         'supervisor', zc.relation.RELATION))

The zc.relation.RELATION describes how to walk back up the chain. Search indexes are explained in reasonable detail in searchindex.rst.

Now that we have added the index, we can search again. The result this time is already computed, so, at least when you ask for tokens, it is repeatable.

>>> res = catalog.findRelationTokens({'supervisor': 'Betty'})
>>> len(list(res))
3
>>> len(list(res))
3
>>> sorted(res) == unindexed
True

Note that the breadth-first sorting is lost when an index is used [10].

Transitive cycles (and updating and removing relations)

The transitive searches and the provided search indexes can handle cycles. Cycles are less likely in the current example than some others, but we can stretch the case a bit: imagine a “king in disguise”, in which someone at the top works lower in the hierarchy. Perhaps Alice works for Zane, who works for Betty, who works for Alice. Artificial, but easy enough to draw:

      ______
     /      \
    /     Zane
   /        |
  /       Alice
 /     __/     \__
/ Betty__         Chuck
\-/  /   \         /   \
   Diane Edgar Frank   Galyn
    |
  Howie

Easy to create too.

>>> z = Employee('Zane', b)
>>> a.supervisor = z

Now we have a cycle. Of course, we have not yet told the catalog about it. index can be used both to reindex Alice and index Zane.

>>> catalog.index(a)
>>> catalog.index(z)

Now, if we ask who works for Betty, we get the entire tree. (We’ll ask for tokens, just so that the result is smaller to look at.) [11]

If we ask for the supervisors of Frank, it will include Betty.

>>> list(catalog.findValueTokens(
...     'supervisor', {zc.relation.RELATION: 'Frank'}))
['Chuck', 'Alice', 'Zane', 'Betty']

Paths returned by findRelationChains are marked with special interfaces, and special metadata, to show the chain.

>>> res = list(catalog.findRelationChains({zc.relation.RELATION: 'Frank'}))
>>> len(res)
5
>>> import zc.relation.interfaces
>>> [zc.relation.interfaces.ICircularRelationPath.providedBy(r)
...  for r in res]
[False, False, False, False, True]

Here’s the last chain:

>>> res[-1] # doctest: +NORMALIZE_WHITESPACE
cycle(<Employee instance "Frank">, <Employee instance "Chuck">,
      <Employee instance "Alice">, <Employee instance "Zane">,
      <Employee instance "Betty">)

The chain’s ‘cycled’ attribute has a list of queries that create a cycle. If you run the query, or queries, you see where the cycle would restart–where the path would have started to overlap. Sometimes the query results will include multiple cycles, and some paths that are not cycles. In this case, there’s only a single cycled query, which results in a single cycled relation.

>>> len(res[4].cycled)
1
>>> list(catalog.findRelations(res[4].cycled[0], maxDepth=1))
[<Employee instance "Alice">]

To remove this craziness [12], we can unindex Zane, and change and reindex Alice.

canFind

We’re to the last search method: canFind. We’ve gotten values and relations, but what if you simply want to know if there is any connection at all? For instance, is Alice a supervisor of Howie? Is Chuck? To answer these questions, you can use the canFind method combined with the targetQuery search argument.

The canFind method takes the same arguments as findRelations. However, it simply returns a boolean about whether the search has any results. This is a convenience that also allows some extra optimizations.

Does Betty supervise anyone?

>>> catalog.canFind({'supervisor': 'Betty'})
True

What about Howie?

>>> catalog.canFind({'supervisor': 'Howie'})
False

What about…Zane (no longer an employee)?

>>> catalog.canFind({'supervisor': 'Zane'})
False

If we want to know if Alice or Chuck supervise Howie, then we want to specify characteristics of two points on a path. To ask a question about the other end of a path, use targetQuery.

Is Alice a supervisor of Howie?

>>> catalog.canFind({'supervisor': 'Alice'},
...                 targetQuery={zc.relation.RELATION: 'Howie'})
True

Is Chuck a supervisor of Howie?

>>> catalog.canFind({'supervisor': 'Chuck'},
...                 targetQuery={zc.relation.RELATION: 'Howie'})
False

Is Howie Alice’s employee?

>>> catalog.canFind({zc.relation.RELATION: 'Howie'},
...                 targetQuery={'supervisor': 'Alice'})
True

Is Howie Chuck’s employee?

>>> catalog.canFind({zc.relation.RELATION: 'Howie'},
...                 targetQuery={'supervisor': 'Chuck'})
False

(Note that, if your relations describe a hierarchy, searching up a hierarchy is usually more efficient than searching down, so the second pair of questions is generally preferable to the first in that case.)

Working with More Complex Relations

So far, our examples have used a simple relation, in which the indexed object is one end of the relation, and the indexed value on the object is the other. This example has let us look at all of the basic zc.relation catalog functionality.

As mentioned in the introduction, though, the catalog supports, and was designed for, more complex relations. This section will quickly examine a few examples of other uses.

In this section, we will see several examples of ideas mentioned above but not yet demonstrated.

  • We can use interface attributes (values or callables) to define value indexes.

  • Using interface attributes will cause an attempt to adapt the relation if it does not already provide the interface.

  • We can use the multiple argument when defining a value index to indicate that the indexed value is a collection.

  • We can use the name argument when defining a value index to specify the name to be used in queries, rather than relying on the name of the interface attribute or callable.

  • The family argument in instantiating the catalog lets you change the default btree family for relations and value indexes from BTrees.family32.IF to BTrees.family64.IF.

Extrinsic Two-Way Relations

A simple variation of our current story is this: what if the indexed relation were between two other objects–that is, what if the relation were extrinsic to both participants?

Let’s imagine we have relations that show biological parentage. We’ll want a “Person” and a “Parentage” relation. We’ll define an interface for IParentage so we can see how using an interface to define a value index works.

>>> class Person(object):
...     def __init__(self, name):
...         self.name = name
...     def __repr__(self):
...         return '<Person %r>' % (self.name,)
...
>>> import zope.interface
>>> class IParentage(zope.interface.Interface):
...     child = zope.interface.Attribute('the child')
...     parents = zope.interface.Attribute('the parents')
...
>>> @zope.interface.implementer(IParentage)
... class Parentage(object):
...
...     def __init__(self, child, parent1, parent2):
...         self.child = child
...         self.parents = (parent1, parent2)
...

Now we’ll define the dumpers and loaders and then the catalog. Notice that we are relying on a pattern: the dump must be called before the load.

>>> _people = {}
>>> _relations = {}
>>> def dumpPeople(obj, catalog, cache):
...     if _people.setdefault(obj.name, obj) is not obj:
...         raise ValueError('we are assuming names are unique')
...     return obj.name
...
>>> def loadPeople(token, catalog, cache):
...     return _people[token]
...
>>> def dumpRelations(obj, catalog, cache):
...     if _relations.setdefault(id(obj), obj) is not obj:
...         raise ValueError('huh?')
...     return id(obj)
...
>>> def loadRelations(token, catalog, cache):
...     return _relations[token]
...
>>> catalog = zc.relation.catalog.Catalog(dumpRelations, loadRelations, family=BTrees.family64)
>>> catalog.addValueIndex(IParentage['child'], dumpPeople, loadPeople,
...                       btree=BTrees.family32.OO)
>>> catalog.addValueIndex(IParentage['parents'], dumpPeople, loadPeople,
...                       btree=BTrees.family32.OO, multiple=True,
...                       name='parent')
>>> catalog.addDefaultQueryFactory(
...     zc.relation.queryfactory.TransposingTransitive(
...         'child', 'parent'))

Now we have a catalog fully set up. Let’s add some relations.

>>> a = Person('Alice')
>>> b = Person('Betty')
>>> c = Person('Charles')
>>> d = Person('Donald')
>>> e = Person('Eugenia')
>>> f = Person('Fred')
>>> g = Person('Gertrude')
>>> h = Person('Harry')
>>> i = Person('Iphigenia')
>>> j = Person('Jacob')
>>> k = Person('Karyn')
>>> l = Person('Lee')
>>> r1 = Parentage(child=j, parent1=k, parent2=l)
>>> r2 = Parentage(child=g, parent1=i, parent2=j)
>>> r3 = Parentage(child=f, parent1=g, parent2=h)
>>> r4 = Parentage(child=e, parent1=g, parent2=h)
>>> r5 = Parentage(child=b, parent1=e, parent2=d)
>>> r6 = Parentage(child=a, parent1=e, parent2=c)

Here’s that in one of our hierarchy diagrams.

Karyn   Lee
     \ /
    Jacob   Iphigenia
         \ /
        Gertrude    Harry
                \  /
             /-------\
         Fred        Eugenia
           Donald   /     \    Charles
                 \ /       \  /
                Betty      Alice

Now we can index the relations, and ask some questions.

>>> for r in (r1, r2, r3, r4, r5, r6):
...     catalog.index(r)
>>> query = catalog.tokenizeQuery
>>> sorted(catalog.findValueTokens(
...     'parent', query(child=a), maxDepth=1))
['Charles', 'Eugenia']
>>> sorted(catalog.findValueTokens('parent', query(child=g)))
['Iphigenia', 'Jacob', 'Karyn', 'Lee']
>>> sorted(catalog.findValueTokens(
...     'child', query(parent=h), maxDepth=1))
['Eugenia', 'Fred']
>>> sorted(catalog.findValueTokens('child', query(parent=h)))
['Alice', 'Betty', 'Eugenia', 'Fred']
>>> catalog.canFind(query(parent=h), targetQuery=query(child=d))
False
>>> catalog.canFind(query(parent=l), targetQuery=query(child=b))
True

Multi-Way Relations

The previous example quickly showed how to set the catalog up for a completely extrinsic two-way relation. The same pattern can be extended for N-way relations. For example, consider a four way relation in the form of SUBJECTS PREDICATE OBJECTS [in CONTEXT]. For instance, we might want to say “(joe,) SELLS (doughnuts, coffee) in corner_store”, where “(joe,)” is the collection of subjects, “SELLS” is the predicate, “(doughnuts, coffee)” is the collection of objects, and “corner_store” is the optional context.

For this last example, we’ll integrate two components we haven’t seen examples of here before: the ZODB and adaptation.

Our example ZODB approach uses OIDs as the tokens. this might be OK in some cases, if you will never support multiple databases and you don’t need an abstraction layer so that a different object can have the same identifier.

>>> import persistent
>>> import struct
>>> class Demo(persistent.Persistent):
...     def __init__(self, name):
...         self.name = name
...     def __repr__(self):
...         return '<Demo instance %r>' % (self.name,)
...
>>> class IRelation(zope.interface.Interface):
...     subjects = zope.interface.Attribute('subjects')
...     predicate = zope.interface.Attribute('predicate')
...     objects = zope.interface.Attribute('objects')
...
>>> class IContextual(zope.interface.Interface):
...     def getContext():
...         'return context'
...     def setContext(value):
...         'set context'
...
>>> @zope.interface.implementer(IContextual)
... class Contextual(object):
...
...     _context = None
...     def getContext(self):
...         return self._context
...     def setContext(self, value):
...         self._context = value
...
>>> @zope.interface.implementer(IRelation)
... class Relation(persistent.Persistent):
...
...     def __init__(self, subjects, predicate, objects):
...         self.subjects = subjects
...         self.predicate = predicate
...         self.objects = objects
...         self._contextual = Contextual()
...
...     def __conform__(self, iface):
...         if iface is IContextual:
...             return self._contextual
...

(When using zope.component, the __conform__ would normally be unnecessary; however, this package does not depend on zope.component.)

>>> def dumpPersistent(obj, catalog, cache):
...     if obj._p_jar is None:
...         catalog._p_jar.add(obj) # assumes something else places it
...     return struct.unpack('<q', obj._p_oid)[0]
...
>>> def loadPersistent(token, catalog, cache):
...     return catalog._p_jar.get(struct.pack('<q', token))
...
>>> from ZODB.tests.util import DB
>>> db = DB()
>>> conn = db.open()
>>> root = conn.root()
>>> catalog = root['catalog'] = zc.relation.catalog.Catalog(
...     dumpPersistent, loadPersistent, family=BTrees.family64)
>>> catalog.addValueIndex(IRelation['subjects'],
...     dumpPersistent, loadPersistent, multiple=True, name='subject')
>>> catalog.addValueIndex(IRelation['objects'],
...     dumpPersistent, loadPersistent, multiple=True, name='object')
>>> catalog.addValueIndex(IRelation['predicate'], btree=BTrees.family32.OO)
>>> catalog.addValueIndex(IContextual['getContext'],
...     dumpPersistent, loadPersistent, name='context')
>>> import transaction
>>> transaction.commit()

The dumpPersistent and loadPersistent is a bit of a toy, as warned above. Also, while our predicate will be stored as a string, some programmers may prefer to have a dump in such a case verify that the string has been explicitly registered in some way, to prevent typos. Obviously, we are not bothering with this for our example.

We make some objects, and then we make some relations with those objects and index them.

>>> joe = root['joe'] = Demo('joe')
>>> sara = root['sara'] = Demo('sara')
>>> jack = root['jack'] = Demo('jack')
>>> ann = root['ann'] = Demo('ann')
>>> doughnuts = root['doughnuts'] = Demo('doughnuts')
>>> coffee = root['coffee'] = Demo('coffee')
>>> muffins = root['muffins'] = Demo('muffins')
>>> cookies = root['cookies'] = Demo('cookies')
>>> newspaper = root['newspaper'] = Demo('newspaper')
>>> corner_store = root['corner_store'] = Demo('corner_store')
>>> bistro = root['bistro'] = Demo('bistro')
>>> bakery = root['bakery'] = Demo('bakery')
>>> SELLS = 'SELLS'
>>> BUYS = 'BUYS'
>>> OBSERVES = 'OBSERVES'
>>> rel1 = root['rel1'] = Relation((joe,), SELLS, (doughnuts, coffee))
>>> IContextual(rel1).setContext(corner_store)
>>> rel2 = root['rel2'] = Relation((sara, jack), SELLS,
...                                (muffins, doughnuts, cookies))
>>> IContextual(rel2).setContext(bakery)
>>> rel3 = root['rel3'] = Relation((ann,), BUYS, (doughnuts,))
>>> rel4 = root['rel4'] = Relation((sara,), BUYS, (bistro,))
>>> for r in (rel1, rel2, rel3, rel4):
...     catalog.index(r)
...

Now we can ask a simple question. Where do they sell doughnuts?

>>> query = catalog.tokenizeQuery
>>> sorted(catalog.findValues(
...     'context',
...     (query(predicate=SELLS, object=doughnuts))),
...     key=lambda ob: ob.name)
[<Demo instance 'bakery'>, <Demo instance 'corner_store'>]

Hopefully these examples give you further ideas on how you can use this tool.

Additional Functionality

This section introduces peripheral functionality. We will learn the following.

  • Listeners can be registered in the catalog. They are alerted when a relation is added, modified, or removed; and when the catalog is cleared and copied (see below).

  • The clear method clears the relations in the catalog.

  • The copy method makes a copy of the current catalog by copying internal data structures, rather than reindexing the relations, which can be a significant optimization opportunity. This copies value indexes and search indexes; and gives listeners an opportunity to specify what, if anything, should be included in the new copy.

  • The ignoreSearchIndex argument to the five pertinent search methods causes the search to ignore search indexes, even if there is an appropriate one.

  • findRelationTokens() (without arguments) returns the BTree set of all relation tokens in the catalog.

  • findValueTokens(INDEX_NAME) (where “INDEX_NAME” should be replaced with an index name) returns the BTree set of all value tokens in the catalog for the given index name.

Listeners

A variety of potential clients may want to be alerted when the catalog changes. zc.relation does not depend on zope.event, so listeners may be registered for various changes. Let’s make a quick demo listener. The additions and removals arguments are dictionaries of {value name: iterable of added or removed value tokens}.

>>> def pchange(d):
...     pprint.pprint(dict(
...         (k, v is not None and sorted(set(v)) or v) for k, v in d.items()))
>>> @zope.interface.implementer(zc.relation.interfaces.IListener)
... class DemoListener(persistent.Persistent):
...
...     def relationAdded(self, token, catalog, additions):
...         print('a relation (token %r) was added to %r '
...                'with these values:' % (token, catalog))
...         pchange(additions)
...     def relationModified(self, token, catalog, additions, removals):
...         print('a relation (token %r) in %r was modified '
...                'with these additions:' % (token, catalog))
...         pchange(additions)
...         print('and these removals:')
...         pchange(removals)
...     def relationRemoved(self, token, catalog, removals):
...         print('a relation (token %r) was removed from %r '
...                'with these values:' % (token, catalog))
...         pchange(removals)
...     def sourceCleared(self, catalog):
...         print('catalog %r had all relations unindexed' % (catalog,))
...     def sourceAdded(self, catalog):
...         print('now listening to catalog %r' % (catalog,))
...     def sourceRemoved(self, catalog):
...         print('no longer listening to catalog %r' % (catalog,))
...     def sourceCopied(self, original, copy):
...         print('catalog %r made a copy %r' % (catalog, copy))
...         copy.addListener(self)
...

Listeners can be installed multiple times.

Listeners can be added as persistent weak references, so that, if they are deleted elsewhere, a ZODB pack will not consider the reference in the catalog to be something preventing garbage collection.

We’ll install one of these demo listeners into our new catalog as a normal reference, the default behavior. Then we’ll show some example messages sent to the demo listener.

>>> listener = DemoListener()
>>> catalog.addListener(listener) # doctest: +ELLIPSIS
now listening to catalog <zc.relation.catalog.Catalog object at ...>
>>> rel5 = root['rel5'] = Relation((ann,), OBSERVES, (newspaper,))
>>> catalog.index(rel5) # doctest: +ELLIPSIS
a relation (token ...) was added to <...Catalog...> with these values:
{'context': None,
 'object': [...],
 'predicate': ['OBSERVES'],
 'subject': [...]}
>>> rel5.subjects = (jack,)
>>> IContextual(rel5).setContext(bistro)
>>> catalog.index(rel5) # doctest: +ELLIPSIS
a relation (token ...) in ...Catalog... was modified with these additions:
{'context': [...], 'subject': [...]}
and these removals:
{'subject': [...]}
>>> catalog.unindex(rel5) # doctest: +ELLIPSIS
a relation (token ...) was removed from <...Catalog...> with these values:
{'context': [...],
 'object': [...],
 'predicate': ['OBSERVES'],
 'subject': [...]}
>>> catalog.removeListener(listener) # doctest: +ELLIPSIS
no longer listening to catalog <...Catalog...>
>>> catalog.index(rel5) # doctest: +ELLIPSIS

The only two methods not shown by those examples are sourceCleared and sourceCopied. We’ll get to those very soon below.

The clear Method

The clear method simply indexes all relations from a catalog. Installed listeners have sourceCleared called.

>>> len(catalog)
5
>>> catalog.addListener(listener) # doctest: +ELLIPSIS
now listening to catalog <zc.relation.catalog.Catalog object at ...>
>>> catalog.clear() # doctest: +ELLIPSIS
catalog <...Catalog...> had all relations unindexed
>>> len(catalog)
0
>>> sorted(catalog.findValues(
...     'context',
...     (query(predicate=SELLS, object=doughnuts))),
...     key=lambda ob: ob.name)
[]

The copy Method

Sometimes you may want to copy a relation catalog. One way of doing this is to create a new catalog, set it up like the current one, and then reindex all the same relations. This is unnecessarily slow for programmer and computer. The copy method makes a new catalog with the same corpus of indexed relations by copying internal data structures.

Search indexes are requested to make new copies of themselves for the new catalog; and listeners are given an opportunity to react as desired to the new copy, including installing themselves, and/or another object of their choosing as a listener.

Let’s make a copy of a populated index with a search index and a listener. Notice in our listener that sourceCopied adds itself as a listener to the new copy. This is done at the very end of the copy process.

>>> for r in (rel1, rel2, rel3, rel4, rel5):
...     catalog.index(r)
... # doctest: +ELLIPSIS
a relation ... was added...
a relation ... was added...
a relation ... was added...
a relation ... was added...
a relation ... was added...
>>> BEGAT = 'BEGAT'
>>> rel6 = root['rel6'] = Relation((jack, ann), BEGAT, (sara,))
>>> henry = root['henry'] = Demo('henry')
>>> rel7 = root['rel7'] = Relation((sara, joe), BEGAT, (henry,))
>>> catalog.index(rel6) # doctest: +ELLIPSIS
a relation (token ...) was added to <...Catalog...> with these values:
{'context': None,
 'object': [...],
 'predicate': ['BEGAT'],
 'subject': [..., ...]}
>>> catalog.index(rel7) # doctest: +ELLIPSIS
a relation (token ...) was added to <...Catalog...> with these values:
{'context': None,
 'object': [...],
 'predicate': ['BEGAT'],
 'subject': [..., ...]}
>>> catalog.addDefaultQueryFactory(
...     zc.relation.queryfactory.TransposingTransitive(
...         'subject', 'object', {'predicate': BEGAT}))
...
>>> list(catalog.findValues(
...     'object', query(subject=jack, predicate=BEGAT)))
[<Demo instance 'sara'>, <Demo instance 'henry'>]
>>> catalog.addSearchIndex(
...     zc.relation.searchindex.TransposingTransitiveMembership(
...         'subject', 'object', static={'predicate': BEGAT}))
>>> sorted(
...     catalog.findValues(
...         'object', query(subject=jack, predicate=BEGAT)),
...     key=lambda o: o.name)
[<Demo instance 'henry'>, <Demo instance 'sara'>]
>>> newcat = root['newcat'] = catalog.copy() # doctest: +ELLIPSIS
catalog <...Catalog...> made a copy <...Catalog...>
now listening to catalog <...Catalog...>
>>> transaction.commit()

Now the copy has its own copies of internal data structures and of the searchindex. For example, let’s modify the relations and add a new one to the copy.

>>> mary = root['mary'] = Demo('mary')
>>> buffy = root['buffy'] = Demo('buffy')
>>> zack = root['zack'] = Demo('zack')
>>> rel7.objects += (mary,)
>>> rel8 = root['rel8'] = Relation((henry, buffy), BEGAT, (zack,))
>>> newcat.index(rel7) # doctest: +ELLIPSIS
a relation (token ...) in ...Catalog... was modified with these additions:
{'object': [...]}
and these removals:
{}
>>> newcat.index(rel8) # doctest: +ELLIPSIS
a relation (token ...) was added to ...Catalog... with these values:
{'context': None,
 'object': [...],
 'predicate': ['BEGAT'],
 'subject': [..., ...]}
>>> len(newcat)
8
>>> sorted(
...     newcat.findValues(
...         'object', query(subject=jack, predicate=BEGAT)),
...     key=lambda o: o.name) # doctest: +NORMALIZE_WHITESPACE
[<Demo instance 'henry'>, <Demo instance 'mary'>, <Demo instance 'sara'>,
 <Demo instance 'zack'>]
>>> sorted(
...     newcat.findValues(
...         'object', query(subject=sara)),
...     key=lambda o: o.name) # doctest: +NORMALIZE_WHITESPACE
[<Demo instance 'bistro'>, <Demo instance 'cookies'>,
<Demo instance 'doughnuts'>, <Demo instance 'henry'>,
<Demo instance 'mary'>, <Demo instance 'muffins'>]

The original catalog is not modified.

>>> len(catalog)
7
>>> sorted(
...     catalog.findValues(
...         'object', query(subject=jack, predicate=BEGAT)),
...     key=lambda o: o.name)
[<Demo instance 'henry'>, <Demo instance 'sara'>]
>>> sorted(
...     catalog.findValues(
...         'object', query(subject=sara)),
...     key=lambda o: o.name) # doctest: +NORMALIZE_WHITESPACE
[<Demo instance 'bistro'>, <Demo instance 'cookies'>,
 <Demo instance 'doughnuts'>, <Demo instance 'henry'>,
 <Demo instance 'muffins'>]

The ignoreSearchIndex argument

The five methods that can use search indexes, findValues, findValueTokens, findRelations, findRelationTokens, and canFind, can be explicitly requested to ignore any pertinent search index using the ignoreSearchIndex argument.

We can see this easily with the token-related methods: the search index result will be a BTree set, while without the search index the result will be a generator.

>>> res1 = newcat.findValueTokens(
...     'object', query(subject=jack, predicate=BEGAT))
>>> res1 # doctest: +ELLIPSIS
LFSet([..., ..., ..., ...])
>>> res2 = newcat.findValueTokens(
...     'object', query(subject=jack, predicate=BEGAT),
...     ignoreSearchIndex=True)
>>> res2 # doctest: +ELLIPSIS
<generator object ... at 0x...>
>>> sorted(res2) == list(res1)
True
>>> res1 = newcat.findRelationTokens(
...     query(subject=jack, predicate=BEGAT))
>>> res1 # doctest: +ELLIPSIS
LFSet([..., ..., ...])
>>> res2 = newcat.findRelationTokens(
...     query(subject=jack, predicate=BEGAT), ignoreSearchIndex=True)
>>> res2 # doctest: +ELLIPSIS
<generator object ... at 0x...>
>>> sorted(res2) == list(res1)
True

We can see that the other methods take the argument, but the results look the same as usual.

>>> res = newcat.findValues(
...     'object', query(subject=jack, predicate=BEGAT),
...     ignoreSearchIndex=True)
>>> res # doctest: +ELLIPSIS
<generator object ... at 0x...>
>>> list(res) == list(newcat.resolveValueTokens(newcat.findValueTokens(
...     'object', query(subject=jack, predicate=BEGAT),
...     ignoreSearchIndex=True), 'object'))
True
>>> res = newcat.findRelations(
...     query(subject=jack, predicate=BEGAT),
...     ignoreSearchIndex=True)
>>> res # doctest: +ELLIPSIS
<generator object ... at 0x...>
>>> list(res) == list(newcat.resolveRelationTokens(
...     newcat.findRelationTokens(
...         query(subject=jack, predicate=BEGAT),
...         ignoreSearchIndex=True)))
True
>>> newcat.canFind(
...     query(subject=jack, predicate=BEGAT), ignoreSearchIndex=True)
True

findRelationTokens()

If you call findRelationTokens without any arguments, you will get the BTree set of all relation tokens in the catalog. This can be handy for tests and for advanced uses of the catalog.

>>> newcat.findRelationTokens() # doctest: +ELLIPSIS
<BTrees.LFBTree.LFTreeSet object at ...>
>>> len(newcat.findRelationTokens())
8
>>> set(newcat.resolveRelationTokens(newcat.findRelationTokens())) == set(
...     (rel1, rel2, rel3, rel4, rel5, rel6, rel7, rel8))
True

findValueTokens(INDEX_NAME)

If you call findValueTokens with only an index name, you will get the BTree structure of all tokens for that value in the index. This can be handy for tests and for advanced uses of the catalog.

>>> newcat.findValueTokens('predicate') # doctest: +ELLIPSIS
<BTrees.OOBTree.OOBTree object at ...>
>>> list(newcat.findValueTokens('predicate'))
['BEGAT', 'BUYS', 'OBSERVES', 'SELLS']

Conclusion

Review

That brings us to the end of our introductory examples. Let’s review, and then look at where you can go from here.

  • Relations are objects with indexed values.

  • The relation catalog indexes relations. The relations can be one-way, two-way, three-way, or N-way, as long as you tell the catalog to index the different values.

  • Creating a catalog:

    • Relations and their values are stored in the catalog as tokens: unique identifiers that you can resolve back to the original value. Integers are the most efficient tokens, but others can work fine too.

    • Token type determines the BTree module needed.

      • If the tokens are 32-bit ints, choose BTrees.family32.II, BTrees.family32.IF or BTrees.family32.IO.

      • If the tokens are 64 bit ints, choose BTrees.family64.II, BTrees.family64.IF or BTrees.family64.IO.

      • If they are anything else, choose BTrees.family32.OI, BTrees.family64.OI, or BTrees.family32.OO (or BTrees.family64.OO–they are the same).

      Within these rules, the choice is somewhat arbitrary unless you plan to merge these results with that of another source that is using a particular BTree module. BTree set operations only work within the same module, so you must match module to module.

    • The family argument in instantiating the catalog lets you change the default btree family for relations and value indexes from BTrees.family32.IF to BTrees.family64.IF.

    • You must define your own functions for tokenizing and resolving tokens. These functions are registered with the catalog for the relations and for each of their value indexes.

    • You add value indexes to relation catalogs to be able to search. Values can be identified to the catalog with callables or interface elements.

      • Using interface attributes will cause an attempt to adapt the relation if it does not already provide the interface.

      • We can use the multiple argument when defining a value index to indicate that the indexed value is a collection. This defaults to False.

      • We can use the name argument when defining a value index to specify the name to be used in queries, rather than relying on the name of the interface attribute or callable.

    • You can set up search indexes to speed up specific searches, usually transitive.

    • Listeners can be registered in the catalog. They are alerted when a relation is added, modified, or removed; and when the catalog is cleared and copied.

  • Catalog Management:

    • Relations are indexed with index(relation), and removed from the catalog with unindex(relation). index_doc(relation_token, relation) and unindex_doc(relation_token) also work.

    • The clear method clears the relations in the catalog.

    • The copy method makes a copy of the current catalog by copying internal data structures, rather than reindexing the relations, which can be a significant optimization opportunity. This copies value indexes and search indexes; and gives listeners an opportunity to specify what, if anything, should be included in the new copy.

  • Searching a catalog:

    • Queries to the relation catalog are formed with dicts.

    • Query keys are the names of the indexes you want to search, or, for the special case of precise relations, the zc.relation.RELATION constant.

    • Query values are the tokens of the results you want to match; or None, indicating relations that have None as a value (or an empty collection, if it is a multiple). Search values can use zc.relation.catalog.any(args) or zc.relation.catalog.Any(args) to specify multiple (non-None) results to match for a given key.

    • The index has a variety of methods to help you work with tokens. tokenizeQuery is typically the most used, though others are available.

    • To find relations that match a query, use findRelations or findRelationTokens. Calling findRelationTokens without any arguments returns the BTree set of all relation tokens in the catalog.

    • To find values that match a query, use findValues or findValueTokens. Calling findValueTokens with only the name of a value index returns the BTree set of all tokens in the catalog for that value index.

    • You search transitively by using a query factory. The zc.relation.queryfactory.TransposingTransitive is a good common case factory that lets you walk up and down a hierarchy. A query factory can be passed in as an argument to search methods as a queryFactory, or installed as a default behavior using addDefaultQueryFactory.

    • To find how a query is related, use findRelationChains or findRelationTokenChains.

    • To find out if a query is related, use canFind.

    • Circular transitive relations are handled to prevent infinite loops. They are identified in findRelationChains and findRelationTokenChains with a zc.relation.interfaces.ICircularRelationPath marker interface.

    • search methods share the following arguments:

      • maxDepth, limiting the transitive depth for searches;

      • filter, allowing code to filter transitive paths;

      • targetQuery, allowing a query to filter transitive paths on the basis of the endpoint;

      • targetFilter, allowing code to filter transitive paths on the basis of the endpoint; and

      • queryFactory, mentioned above.

      In addition, the ignoreSearchIndex argument to findRelations, findRelationTokens, findValues, findValueTokens, and canFind causes the search to ignore search indexes, even if there is an appropriate one.

Next Steps

If you want to read more, next steps depend on how you like to learn. Here are some of the other documents in the zc.relation package.

optimization.rst:

Best practices for optimizing your use of the relation catalog.

searchindex.rst:

Queries factories and search indexes: from basics to nitty gritty details.

tokens.rst:

This document explores the details of tokens. All God’s chillun love tokens, at least if God’s chillun are writing non-toy apps using zc.relation. It includes discussion of the token helpers that the catalog provides, how to use zope.app.intid-like registries with zc.relation, how to use tokens to “join” query results reasonably efficiently, and how to index joins. It also is unnecessarily mind-blowing because of the examples used.

interfaces.py:

The contract, for nuts and bolts.

Finally, the truly die-hard might also be interested in the timeit directory, which holds scripts used to test assumptions and learn.

Tokens and Joins: zc.relation Catalog Extended Example

Introduction and Set Up

This document assumes you have read the introductory README.rst and want to learn a bit more by example. In it, we will explore a more complicated set of relations that demonstrates most of the aspects of working with tokens. In particular, we will look at joins, which will also give us a chance to look more in depth at query factories and search indexes, and introduce the idea of listeners. It will not explain the basics that the README already addressed.

Imagine we are indexing security assertions in a system. In this system, users may have roles within an organization. Each organization may have multiple child organizations and may have a single parent organization. A user with a role in a parent organization will have the same role in all transitively connected child relations.

We have two kinds of relations, then. One kind of relation will model the hierarchy of organizations. We’ll do it with an intrinsic relation of organizations to their children: that reflects the fact that parent organizations choose and are comprised of their children; children do not choose their parents.

The other relation will model the (multiple) roles a (single) user has in a (single) organization. This relation will be entirely extrinsic.

We could create two catalogs, one for each type. Or we could put them both in the same catalog. Initially, we’ll go with the single-catalog approach for our examples. This single catalog, then, will be indexing a heterogeneous collection of relations.

Let’s define the two relations with interfaces. We’ll include one accessor, getOrganization, largely to show how to handle methods.

>>> import zope.interface
>>> class IOrganization(zope.interface.Interface):
...     title = zope.interface.Attribute('the title')
...     parts = zope.interface.Attribute(
...         'the organizations that make up this one')
...
>>> class IRoles(zope.interface.Interface):
...     def getOrganization():
...         'return the organization in which this relation operates'
...     principal_id = zope.interface.Attribute(
...         'the pricipal id whose roles this relation lists')
...     role_ids = zope.interface.Attribute(
...         'the role ids that the principal explicitly has in the '
...         'organization.  The principal may have other roles via '
...         'roles in parent organizations.')
...

Now we can create some classes. In the README example, the setup was a bit of a toy. This time we will be just a bit more practical. We’ll also expect to be operating within the ZODB, with a root and transactions. [14]

Here’s how we will dump and load our relations: use a “registry” object, similar to an intid utility. [15]

In this implementation of the “dump” method, we use the cache just to show you how you might use it. It probably is overkill for this job, and maybe even a speed loss, but you can see the idea.

>>> def dump(obj, catalog, cache):
...     reg = cache.get('registry')
...     if reg is None:
...         reg = cache['registry'] = catalog._p_jar.root()['registry']
...     return reg.getId(obj)
...
>>> def load(token, catalog, cache):
...     reg = cache.get('registry')
...     if reg is None:
...         reg = cache['registry'] = catalog._p_jar.root()['registry']
...     return reg.getObject(token)
...

Now we can create a relation catalog to hold these items.

>>> import zc.relation.catalog
>>> catalog = root['catalog'] = zc.relation.catalog.Catalog(dump, load)
>>> transaction.commit()

Now we set up our indexes. We’ll start with just the organizations, and set up the catalog with them. This part will be similar to the example in README.rst, but will introduce more discussions of optimizations and tokens. Then we’ll add in the part about roles, and explore queries and token-based “joins”.

Organizations

The organization will hold a set of organizations. This is actually not inherently easy in the ZODB because this means that we need to compare or hash persistent objects, which does not work reliably over time and across machines out-of-the-box. To side-step the issue for this example, and still do something a bit interesting and real-world, we’ll use the registry tokens introduced above. This will also give us a chance to talk a bit more about optimizations and tokens. (If you would like to sanely and transparently hold a set of persistent objects, try the zc.set package XXX not yet.)

>>> import BTrees
>>> import persistent
>>> @zope.interface.implementer(IOrganization)
... @total_ordering
... class Organization(persistent.Persistent):
...
...     def __init__(self, title):
...         self.title = title
...         self.parts = BTrees.family32.IF.TreeSet()
...     # the next parts just make the tests prettier
...     def __repr__(self):
...         return '<Organization instance "' + self.title + '">'
...     def __lt__(self, other):
...         # pukes if other doesn't have name
...         return self.title < other.title
...     def __eq__(self, other):
...         return self is other
...     def __hash__(self):
...         return 1  # dummy
...

OK, now we know how organizations will work. Now we can add the parts index to the catalog. This will do a few new things from how we added indexes in the README.

>>> catalog.addValueIndex(IOrganization['parts'], multiple=True,
...                       name="part")

So, what’s different from the README examples?

First, we are using an interface element to define the value to be indexed. It provides an interface to which objects will be adapted, a default name for the index, and information as to whether the attribute should be used directly or called.

Second, we are not specifying a dump or load. They are None. This means that the indexed value can already be treated as a token. This can allow a very significant optimization for reindexing if the indexed value is a large collection using the same BTree family as the index–which leads us to the next difference.

Third, we are specifying that multiple=True. This means that the value on a given relation that provides or can be adapted to IOrganization will have a collection of parts. These will always be regarded as a set, whether the actual colection is a BTrees set or the keys of a BTree.

Last, we are specifying a name to be used for queries. I find that queries read more easily when the query keys are singular, so I often rename plurals.

As in the README, We can add another simple transposing transitive query factory, switching between ‘part’ and None.

>>> import zc.relation.queryfactory
>>> factory1 = zc.relation.queryfactory.TransposingTransitive(
...     'part', None)
>>> catalog.addDefaultQueryFactory(factory1)

Let’s add a couple of search indexes in too, of the hierarchy looking up…

>>> import zc.relation.searchindex
>>> catalog.addSearchIndex(
...     zc.relation.searchindex.TransposingTransitiveMembership(
...         'part', None))

…and down.

>>> catalog.addSearchIndex(
...     zc.relation.searchindex.TransposingTransitiveMembership(
...         None, 'part'))

PLEASE NOTE: the search index looking up is not a good idea practically. The index is designed for looking down [16].

Let’s create and add a few organizations.

We’ll make a structure like this [24]:

        Ynod Corp Mangement                 Zookd Corp Management
         /      |      \                       /      |      \
  Ynod Devs  Ynod SAs  Ynod Admins  Zookd Admins   Zookd SAs  Zookd Devs
    /      \              \                 /                /         \
Y3L4 Proj  Bet Proj      Ynod Zookd Task Force      Zookd hOgnmd     Zookd Nbd

Here’s the Python.

>>> orgs = root['organizations'] = BTrees.family32.OO.BTree()
>>> for nm, parts in (
...     ('Y3L4 Proj', ()),
...     ('Bet Proj', ()),
...     ('Ynod Zookd Task Force', ()),
...     ('Zookd hOgnmd', ()),
...     ('Zookd Nbd', ()),
...     ('Ynod Devs', ('Y3L4 Proj', 'Bet Proj')),
...     ('Ynod SAs', ()),
...     ('Ynod Admins', ('Ynod Zookd Task Force',)),
...     ('Zookd Admins', ('Ynod Zookd Task Force',)),
...     ('Zookd SAs', ()),
...     ('Zookd Devs', ('Zookd hOgnmd', 'Zookd Nbd')),
...     ('Ynod Corp Management', ('Ynod Devs', 'Ynod SAs', 'Ynod Admins')),
...     ('Zookd Corp Management', ('Zookd Devs', 'Zookd SAs',
...                                'Zookd Admins'))):
...     org = Organization(nm)
...     for part in parts:
...         ignore = org.parts.insert(registry.getId(orgs[part]))
...     orgs[nm] = org
...     catalog.index(org)
...

Now the catalog knows about the relations.

>>> len(catalog)
13
>>> root['dummy'] = Organization('Foo')
>>> root['dummy'] in catalog
False
>>> orgs['Y3L4 Proj'] in catalog
True

Also, now we can search. To do this, we can use some of the token methods that the catalog provides. The most commonly used is tokenizeQuery. It takes a query with values that are not tokenized and converts them to values that are tokenized.

>>> Ynod_SAs_id = registry.getId(orgs['Ynod SAs'])
>>> catalog.tokenizeQuery({None: orgs['Ynod SAs']}) == {
...     None: Ynod_SAs_id}
True
>>> Zookd_SAs_id = registry.getId(orgs['Zookd SAs'])
>>> Zookd_Devs_id = registry.getId(orgs['Zookd Devs'])
>>> catalog.tokenizeQuery(
...     {None: zc.relation.catalog.any(
...         orgs['Zookd SAs'], orgs['Zookd Devs'])}) == {
...     None: zc.relation.catalog.any(Zookd_SAs_id, Zookd_Devs_id)}
True

Of course, right now doing this with ‘part’ alone is kind of silly, since it does not change within the relation catalog (because we said that dump and load were None, as discussed above).

>>> catalog.tokenizeQuery({'part': Ynod_SAs_id}) == {
...     'part': Ynod_SAs_id}
True
>>> catalog.tokenizeQuery(
...     {'part': zc.relation.catalog.any(Zookd_SAs_id, Zookd_Devs_id)}
...     ) == {'part': zc.relation.catalog.any(Zookd_SAs_id, Zookd_Devs_id)}
True

The tokenizeQuery method is so common that we’re going to assign it to a variable in our example. Then we’ll do a search or two.

So…find the relations that Ynod Devs supervise.

>>> t = catalog.tokenizeQuery
>>> res = list(catalog.findRelationTokens(t({None: orgs['Ynod Devs']})))

OK…we used findRelationTokens, as opposed to findRelations, so res is a couple of numbers now. How do we convert them back? resolveRelationTokens will do the trick.

>>> len(res)
3
>>> sorted(catalog.resolveRelationTokens(res))
... # doctest: +NORMALIZE_WHITESPACE
[<Organization instance "Bet Proj">, <Organization instance "Y3L4 Proj">,
 <Organization instance "Ynod Devs">]

resolveQuery is the mirror image of tokenizeQuery: it converts tokenized queries to queries with “loaded” values.

>>> original = {'part': zc.relation.catalog.any(
...                 Zookd_SAs_id, Zookd_Devs_id),
...             None: orgs['Zookd Devs']}
>>> tokenized = catalog.tokenizeQuery(original)
>>> original == catalog.resolveQuery(tokenized)
True
>>> original = {None: zc.relation.catalog.any(
...                 orgs['Zookd SAs'], orgs['Zookd Devs']),
...             'part': Zookd_Devs_id}
>>> tokenized = catalog.tokenizeQuery(original)
>>> original == catalog.resolveQuery(tokenized)
True

Likewise, tokenizeRelations is the mirror image of resolveRelationTokens.

>>> sorted(catalog.tokenizeRelations(
...     [orgs["Bet Proj"], orgs["Y3L4 Proj"]])) == sorted(
...     registry.getId(o) for o in
...     [orgs["Bet Proj"], orgs["Y3L4 Proj"]])
True

The other token-related methods are as follows [17]:

  • tokenizeValues, which returns an iterable of tokens for the values of the given index name;

  • resolveValueTokens, which returns an iterable of values for the tokens of the given index name;

  • tokenizeRelation, which returns a token for the given relation; and

  • resolveRelationToken, which returns a relation for the given token.

Why do we bother with these tokens, instead of hiding them away and making the API prettier? By exposing them, we enable efficient joining, and efficient use in other contexts. For instance, if you use the same intid utility to tokenize in other catalogs, our results can be merged with the results of other catalogs. Similarly, you can use the results of queries to other catalogs–or even “joins” from earlier results of querying this catalog–as query values here. We’ll explore this in the next section.

Roles

We have set up the Organization relations. Now let’s set up the roles, and actually be able to answer the questions that we described at the beginning of the document.

In our Roles object, roles and principals will simply be strings–ids, if this were a real system. The organization will be a direct object reference.

>>> @zope.interface.implementer(IRoles)
... @total_ordering
... class Roles(persistent.Persistent):
...
...     def __init__(self, principal_id, role_ids, organization):
...         self.principal_id = principal_id
...         self.role_ids = BTrees.family32.OI.TreeSet(role_ids)
...         self._organization = organization
...     def getOrganization(self):
...         return self._organization
...     # the rest is for prettier/easier tests
...     def __repr__(self):
...         return "<Roles instance (%s has %s in %s)>" % (
...             self.principal_id, ', '.join(self.role_ids),
...             self._organization.title)
...     def __lt__(self, other):
...         _self = (
...             self.principal_id,
...             tuple(self.role_ids),
...             self._organization.title,
...         )
...         _other = (
...             other.principal_id,
...             tuple(other.role_ids),
...             other._organization.title,
...         )
...         return _self <_other
...     def __eq__(self, other):
...         return self is other
...     def __hash__(self):
...         return 1  # dummy
...

Now let’s add add the value indexes to the relation catalog.

>>> catalog.addValueIndex(IRoles['principal_id'], btree=BTrees.family32.OI)
>>> catalog.addValueIndex(IRoles['role_ids'], btree=BTrees.family32.OI,
...                       multiple=True, name='role_id')
>>> catalog.addValueIndex(IRoles['getOrganization'], dump, load,
...                       name='organization')

Those are some slightly new variations of what we’ve seen in addValueIndex before, but all mixing and matching on the same ingredients.

As a reminder, here is our organization structure:

        Ynod Corp Mangement                 Zookd Corp Management
         /      |      \                       /      |      \
  Ynod Devs  Ynod SAs  Ynod Admins  Zookd Admins   Zookd SAs  Zookd Devs
    /      \              \                 /                /         \
Y3L4 Proj  Bet Proj      Ynod Zookd Task Force      Zookd hOgnmd     Zookd Nbd

Now let’s create and add some roles.

>>> principal_ids = [
...     'abe', 'bran', 'cathy', 'david', 'edgar', 'frank', 'gertrude',
...     'harriet', 'ignas', 'jacob', 'karyn', 'lettie', 'molly', 'nancy',
...     'ophelia', 'pat']
>>> role_ids = ['user manager', 'writer', 'reviewer', 'publisher']
>>> get_role = dict((v[0], v) for v in role_ids).__getitem__
>>> roles = root['roles'] = BTrees.family32.IO.BTree()
>>> next = 0
>>> for prin, org, role_ids in (
...     ('abe', orgs['Zookd Corp Management'], 'uwrp'),
...     ('bran', orgs['Ynod Corp Management'], 'uwrp'),
...     ('cathy', orgs['Ynod Devs'], 'w'),
...     ('cathy', orgs['Y3L4 Proj'], 'r'),
...     ('david', orgs['Bet Proj'], 'wrp'),
...     ('edgar', orgs['Ynod Devs'], 'up'),
...     ('frank', orgs['Ynod SAs'], 'uwrp'),
...     ('frank', orgs['Ynod Admins'], 'w'),
...     ('gertrude', orgs['Ynod Zookd Task Force'], 'uwrp'),
...     ('harriet', orgs['Ynod Zookd Task Force'], 'w'),
...     ('harriet', orgs['Ynod Admins'], 'r'),
...     ('ignas', orgs['Zookd Admins'], 'r'),
...     ('ignas', orgs['Zookd Corp Management'], 'w'),
...     ('karyn', orgs['Zookd Corp Management'], 'uwrp'),
...     ('karyn', orgs['Ynod Corp Management'], 'uwrp'),
...     ('lettie', orgs['Zookd Corp Management'], 'u'),
...     ('lettie', orgs['Ynod Zookd Task Force'], 'w'),
...     ('lettie', orgs['Zookd SAs'], 'w'),
...     ('molly', orgs['Zookd SAs'], 'uwrp'),
...     ('nancy', orgs['Zookd Devs'], 'wrp'),
...     ('nancy', orgs['Zookd hOgnmd'], 'u'),
...     ('ophelia', orgs['Zookd Corp Management'], 'w'),
...     ('ophelia', orgs['Zookd Devs'], 'r'),
...     ('ophelia', orgs['Zookd Nbd'], 'p'),
...     ('pat', orgs['Zookd Nbd'], 'wrp')):
...     assert prin in principal_ids
...     role_ids = [get_role(l) for l in role_ids]
...     role = roles[next] = Roles(prin, role_ids, org)
...     role.key = next
...     next += 1
...     catalog.index(role)
...

Now we can begin to do searches [18].

What are all the role settings for ophelia?

>>> sorted(catalog.findRelations({'principal_id': 'ophelia'}))
... # doctest: +NORMALIZE_WHITESPACE
[<Roles instance (ophelia has publisher in Zookd Nbd)>,
 <Roles instance (ophelia has reviewer in Zookd Devs)>,
 <Roles instance (ophelia has writer in Zookd Corp Management)>]

That answer does not need to be transitive: we’re done.

Next question. Where does ophelia have the ‘writer’ role?

>>> list(catalog.findValues(
...     'organization', {'principal_id': 'ophelia',
...                        'role_id': 'writer'}))
[<Organization instance "Zookd Corp Management">]

Well, that’s correct intransitively. Do we need a transitive queries factory? No! This is a great chance to look at the token join we talked about in the previous section. This should actually be a two-step operation: find all of the organizations in which ophelia has writer, and then find all of the transitive parts to that organization.

>>> sorted(catalog.findRelations({None: zc.relation.catalog.Any(
...     catalog.findValueTokens('organization',
...                             {'principal_id': 'ophelia',
...                              'role_id': 'writer'}))}))
... # doctest: +NORMALIZE_WHITESPACE
[<Organization instance "Ynod Zookd Task Force">,
 <Organization instance "Zookd Admins">,
 <Organization instance "Zookd Corp Management">,
 <Organization instance "Zookd Devs">,
 <Organization instance "Zookd Nbd">,
 <Organization instance "Zookd SAs">,
 <Organization instance "Zookd hOgnmd">]

That’s more like it.

Next question. What users have roles in the ‘Zookd Devs’ organization? Intransitively, that’s pretty easy.

>>> sorted(catalog.findValueTokens(
...     'principal_id', t({'organization': orgs['Zookd Devs']})))
['nancy', 'ophelia']

Transitively, we should do another join.

>>> org_id = registry.getId(orgs['Zookd Devs'])
>>> sorted(catalog.findValueTokens(
...     'principal_id', {
...         'organization': zc.relation.catalog.any(
...             org_id, *catalog.findRelationTokens({'part': org_id}))}))
['abe', 'ignas', 'karyn', 'lettie', 'nancy', 'ophelia']

That’s a little awkward, but it does the trick.

Last question, and the kind of question that started the entire example.

What roles does ophelia have in the “Zookd Nbd” organization?

>>> list(catalog.findValueTokens(
...     'role_id', t({'organization': orgs['Zookd Nbd'],
...                   'principal_id': 'ophelia'})))
['publisher']

Intransitively, that’s correct. But, transitively, ophelia also has reviewer and writer, and that’s the answer we want to be able to get quickly.

We could ask the question a different way, then, again leveraging a join. We’ll set it up as a function, because we will want to use it a little later without repeating the code.

>>> def getRolesInOrganization(principal_id, org):
...     org_id = registry.getId(org)
...     return sorted(catalog.findValueTokens(
...         'role_id', {
...             'organization': zc.relation.catalog.any(
...                 org_id,
...                 *catalog.findRelationTokens({'part': org_id})),
...             'principal_id': principal_id}))
...
>>> getRolesInOrganization('ophelia', orgs['Zookd Nbd'])
['publisher', 'reviewer', 'writer']

As you can see, then, working with tokens makes interesting joins possible, as long as the tokens are the same across the two queries.

We have examined tokens methods and token techniques like joins. The example story we have told can let us get into a few more advanced topics, such as query factory joins and search indexes that can increase their read speed.

Query Factory Joins

We can build a query factory that makes the join automatic. A query factory is a callable that takes two arguments: a query (the one that starts the search) and the catalog. The factory either returns None, indicating that the query factory cannot be used for this query, or it returns another callable that takes a chain of relations. The last token in the relation chain is the most recent. The output of this inner callable is expected to be an iterable of BTrees.family32.OO.Bucket queries to search further from the given chain of relations.

Here’s a flawed approach to this problem.

>>> def flawed_factory(query, catalog):
...     if (len(query) == 2 and
...         'organization' in query and
...         'principal_id' in query):
...         def getQueries(relchain):
...             if not relchain:
...                 yield query
...                 return
...             current = catalog.getValueTokens(
...                 'organization', relchain[-1])
...             if current:
...                 organizations = catalog.getRelationTokens(
...                     {'part': zc.relation.catalog.Any(current)})
...                 if organizations:
...                     res = BTrees.family32.OO.Bucket(query)
...                     res['organization'] = zc.relation.catalog.Any(
...                         organizations)
...                     yield res
...         return getQueries
...

That works for our current example.

>>> sorted(catalog.findValueTokens(
...     'role_id', t({'organization': orgs['Zookd Nbd'],
...                   'principal_id': 'ophelia'}),
...     queryFactory=flawed_factory))
['publisher', 'reviewer', 'writer']

However, it won’t work for other similar queries.

>>> getRolesInOrganization('abe', orgs['Zookd Nbd'])
['publisher', 'reviewer', 'user manager', 'writer']
>>> sorted(catalog.findValueTokens(
...     'role_id', t({'organization': orgs['Zookd Nbd'],
...                   'principal_id': 'abe'}),
...     queryFactory=flawed_factory))
[]

oops.

The flawed_factory is actually a useful pattern for more typical relation traversal. It goes from relation to relation to relation, and ophelia has connected relations all the way to the top. However, abe only has them at the top, so nothing is traversed.

Instead, we can make a query factory that modifies the initial query.

>>> def factory2(query, catalog):
...     if (len(query) == 2 and
...         'organization' in query and
...         'principal_id' in query):
...         def getQueries(relchain):
...             if not relchain:
...                 res = BTrees.family32.OO.Bucket(query)
...                 org_id = query['organization']
...                 if org_id is not None:
...                     res['organization'] = zc.relation.catalog.any(
...                         org_id,
...                         *catalog.findRelationTokens({'part': org_id}))
...                 yield res
...         return getQueries
...
>>> sorted(catalog.findValueTokens(
...     'role_id', t({'organization': orgs['Zookd Nbd'],
...                   'principal_id': 'ophelia'}),
...     queryFactory=factory2))
['publisher', 'reviewer', 'writer']
>>> sorted(catalog.findValueTokens(
...     'role_id', t({'organization': orgs['Zookd Nbd'],
...                   'principal_id': 'abe'}),
...     queryFactory=factory2))
['publisher', 'reviewer', 'user manager', 'writer']

A difference between this and the other approach is that it is essentially intransitive: this query factory modifies the initial query, and then does not give further queries. The catalog currently always stops calling the query factory if the queries do not return any results, so an approach like the flawed_factory simply won’t work for this kind of problem.

We could add this query factory as another default.

>>> catalog.addDefaultQueryFactory(factory2)
>>> sorted(catalog.findValueTokens(
...     'role_id', t({'organization': orgs['Zookd Nbd'],
...                   'principal_id': 'ophelia'})))
['publisher', 'reviewer', 'writer']
>>> sorted(catalog.findValueTokens(
...     'role_id', t({'organization': orgs['Zookd Nbd'],
...                   'principal_id': 'abe'})))
['publisher', 'reviewer', 'user manager', 'writer']

The previously installed query factory is still available.

>>> list(catalog.iterDefaultQueryFactories()) == [factory1, factory2]
True
>>> list(catalog.findRelations(
...     {'part': registry.getId(orgs['Y3L4 Proj'])}))
...     # doctest: +NORMALIZE_WHITESPACE
[<Organization instance "Ynod Devs">,
 <Organization instance "Ynod Corp Management">]
>>> sorted(catalog.findRelations(
...     {None: registry.getId(orgs['Ynod Corp Management'])}))
...     # doctest: +NORMALIZE_WHITESPACE
[<Organization instance "Bet Proj">, <Organization instance "Y3L4 Proj">,
 <Organization instance "Ynod Admins">,
 <Organization instance "Ynod Corp Management">,
 <Organization instance "Ynod Devs">, <Organization instance "Ynod SAs">,
 <Organization instance "Ynod Zookd Task Force">]

Search Index for Query Factory Joins

Now that we have written a query factory that encapsulates the join, we can use a search index that speeds it up. We’ve only used transitive search indexes so far. Now we will add an intransitive search index.

The intransitive search index generally just needs the search value names it should be indexing, optionally the result name (defaulting to relations), and optionally the query factory to be used.

We need to use two additional options because of the odd join trick we’re doing. We need to specify what organization and principal_id values need to be changed when an object is indexed, and we need to indicate that we should update when organization, principal_id, or parts changes.

getValueTokens specifies the values that need to be indexed. It gets the index, the name for the tokens desired, the token, the catalog that generated the token change (it may not be the same as the index’s catalog, the source dictionary that contains a dictionary of the values that will be used for tokens if you do not override them, a dict of the added values for this token (keys are value names), a dict of the removed values for this token, and whether the token has been removed. The method can return None, which will leave the index to its default behavior that should work if no query factory is used; or an iterable of values.

>>> def getValueTokens(index, name, token, catalog, source,
...                    additions, removals, removed):
...     if name == 'organization':
...         orgs = source.get('organization')
...         if not removed or not orgs:
...             orgs = index.catalog.getValueTokens(
...                 'organization', token)
...             if not orgs:
...                 orgs = [token]
...                 orgs.extend(removals.get('part', ()))
...         orgs = set(orgs)
...         orgs.update(index.catalog.findValueTokens(
...             'part',
...             {None: zc.relation.catalog.Any(
...                 t for t in orgs if t is not None)}))
...         return orgs
...     elif name == 'principal_id':
...         # we only want custom behavior if this is an organization
...         if 'principal_id' in source or index.catalog.getValueTokens(
...             'principal_id', token):
...             return ''
...         orgs = set((token,))
...         orgs.update(index.catalog.findRelationTokens(
...             {'part': token}))
...         return set(index.catalog.findValueTokens(
...             'principal_id', {
...                 'organization': zc.relation.catalog.Any(orgs)}))
...
>>> index = zc.relation.searchindex.Intransitive(
...     ('organization', 'principal_id'), 'role_id', factory2,
...     getValueTokens,
...     ('organization', 'principal_id', 'part', 'role_id'),
...     unlimitedDepth=True)
>>> catalog.addSearchIndex(index)
>>> res = catalog.findValueTokens(
...     'role_id', t({'organization': orgs['Zookd Nbd'],
...                   'principal_id': 'ophelia'}))
>>> list(res)
['publisher', 'reviewer', 'writer']
>>> list(res)
['publisher', 'reviewer', 'writer']
>>> res = catalog.findValueTokens(
...     'role_id', t({'organization': orgs['Zookd Nbd'],
...                   'principal_id': 'abe'}))
>>> list(res)
['publisher', 'reviewer', 'user manager', 'writer']
>>> list(res)
['publisher', 'reviewer', 'user manager', 'writer']

[19]

Now we can change and remove relations–both organizations and roles–and have the index maintain correct state. Given the current state of organizations–

        Ynod Corp Mangement                 Zookd Corp Management
         /      |      \                       /      |      \
  Ynod Devs  Ynod SAs  Ynod Admins  Zookd Admins   Zookd SAs  Zookd Devs
    /      \              \                 /                /         \
Y3L4 Proj  Bet Proj      Ynod Zookd Task Force      Zookd hOgnmd     Zookd Nbd

–first we will move Ynod Devs to beneath Zookd Devs, and back out. This will briefly give abe full privileges to Y3L4 Proj., among others.

>>> list(catalog.findValueTokens(
...     'role_id', t({'organization': orgs['Y3L4 Proj'],
...                   'principal_id': 'abe'})))
[]
>>> orgs['Zookd Devs'].parts.insert(registry.getId(orgs['Ynod Devs']))
1
>>> catalog.index(orgs['Zookd Devs'])
>>> res = catalog.findValueTokens(
...     'role_id', t({'organization': orgs['Y3L4 Proj'],
...                   'principal_id': 'abe'}))
>>> list(res)
['publisher', 'reviewer', 'user manager', 'writer']
>>> list(res)
['publisher', 'reviewer', 'user manager', 'writer']
>>> orgs['Zookd Devs'].parts.remove(registry.getId(orgs['Ynod Devs']))
>>> catalog.index(orgs['Zookd Devs'])
>>> list(catalog.findValueTokens(
...     'role_id', t({'organization': orgs['Y3L4 Proj'],
...                   'principal_id': 'abe'})))
[]

As another example, we will change the roles abe has, and see that it is propagated down to Zookd Nbd.

>>> rels = list(catalog.findRelations(t(
...     {'principal_id': 'abe',
...      'organization': orgs['Zookd Corp Management']})))
>>> len(rels)
1
>>> rels[0].role_ids.remove('reviewer')
>>> catalog.index(rels[0])
>>> res = catalog.findValueTokens(
...     'role_id', t({'organization': orgs['Zookd Nbd'],
...                   'principal_id': 'abe'}))
>>> list(res)
['publisher', 'user manager', 'writer']
>>> list(res)
['publisher', 'user manager', 'writer']

Note that search index order matters. In our case, our intransitive search index is relying on our transitive index, so the transitive index needs to come first. You want transitive relation indexes before name. Right now, you are in charge of this order: it will be difficult to come up with a reliable algorithm for guessing this.

Listeners, Catalog Administration, and Joining Across Relation Catalogs

We’ve done all of our examples so far with a single catalog that indexes both kinds of relations. What if we want to have two catalogs with homogenous collections of relations? That can feel cleaner, but it also introduces some new wrinkles.

Let’s use our current catalog for organizations, removing the extra information; and create a new one for roles.

>>> role_catalog = root['role_catalog'] = catalog.copy()
>>> transaction.commit()
>>> org_catalog = catalog
>>> del catalog

We’ll need a slightly different query factory and a slightly different search index getValueTokens function. We’ll write those, then modify the configuration of our two catalogs for the new world.

The transitive factory we write here is for the role catalog. It needs access to the organzation catalog. We could do this a variety of ways–relying on a utility, or finding the catalog from context. We will make the role_catalog have a .org_catalog attribute, and rely on that.

>>> role_catalog.org_catalog = org_catalog
>>> def factory3(query, catalog):
...     if (len(query) == 2 and
...         'organization' in query and
...         'principal_id' in query):
...         def getQueries(relchain):
...             if not relchain:
...                 res = BTrees.family32.OO.Bucket(query)
...                 org_id = query['organization']
...                 if org_id is not None:
...                     res['organization'] = zc.relation.catalog.any(
...                         org_id,
...                         *catalog.org_catalog.findRelationTokens(
...                             {'part': org_id}))
...                 yield res
...         return getQueries
...
>>> def getValueTokens2(index, name, token, catalog, source,
...                    additions, removals, removed):
...     is_role_catalog = catalog is index.catalog # role_catalog
...     if name == 'organization':
...         if is_role_catalog:
...             orgs = set(source.get('organization') or
...                        index.catalog.getValueTokens(
...                         'organization', token) or ())
...         else:
...             orgs = set((token,))
...             orgs.update(removals.get('part', ()))
...         orgs.update(index.catalog.org_catalog.findValueTokens(
...             'part',
...             {None: zc.relation.catalog.Any(
...                 t for t in orgs if t is not None)}))
...         return orgs
...     elif name == 'principal_id':
...         # we only want custom behavior if this is an organization
...         if not is_role_catalog:
...             orgs = set((token,))
...             orgs.update(index.catalog.org_catalog.findRelationTokens(
...                 {'part': token}))
...             return set(index.catalog.findValueTokens(
...                 'principal_id', {
...                     'organization': zc.relation.catalog.Any(orgs)}))
...     return ''

If you are following along in the code and comparing to the originals, you may see that this approach is a bit cleaner than the one when the relations were in the same catalog.

Now we will fix up the the organization catalog [20].

This also shows using the removeDefaultQueryFactory and removeSearchIndex methods [21].

Now we will set up the role catalog [22].

The new role_catalog index needs to be updated from the org_catalog. We’ll set that up using listeners, a new concept.

>>> org_catalog.addListener(index2)
>>> list(org_catalog.iterListeners()) == [index2]
True

Now the role_catalog should be able to answer the same questions as the old single catalog approach.

>>> t = role_catalog.tokenizeQuery
>>> list(role_catalog.findValueTokens(
...     'role_id', t({'organization': orgs['Zookd Nbd'],
...                   'principal_id': 'abe'})))
['publisher', 'user manager', 'writer']
>>> list(role_catalog.findValueTokens(
...     'role_id', t({'organization': orgs['Zookd Nbd'],
...                   'principal_id': 'ophelia'})))
['publisher', 'reviewer', 'writer']

We can also make changes to both catalogs and the search indexes are maintained.

>>> list(role_catalog.findValueTokens(
...     'role_id', t({'organization': orgs['Y3L4 Proj'],
...                   'principal_id': 'abe'})))
[]
>>> orgs['Zookd Devs'].parts.insert(registry.getId(orgs['Ynod Devs']))
1
>>> org_catalog.index(orgs['Zookd Devs'])
>>> list(role_catalog.findValueTokens(
...     'role_id', t({'organization': orgs['Y3L4 Proj'],
...                   'principal_id': 'abe'})))
['publisher', 'user manager', 'writer']
>>> orgs['Zookd Devs'].parts.remove(registry.getId(orgs['Ynod Devs']))
>>> org_catalog.index(orgs['Zookd Devs'])
>>> list(role_catalog.findValueTokens(
...     'role_id', t({'organization': orgs['Y3L4 Proj'],
...                   'principal_id': 'abe'})))
[]
>>> rels = list(role_catalog.findRelations(t(
...     {'principal_id': 'abe',
...      'organization': orgs['Zookd Corp Management']})))
>>> len(rels)
1
>>> rels[0].role_ids.insert('reviewer')
1
>>> role_catalog.index(rels[0])
>>> res = role_catalog.findValueTokens(
...     'role_id', t({'organization': orgs['Zookd Nbd'],
...                   'principal_id': 'abe'}))
>>> list(res)
['publisher', 'reviewer', 'user manager', 'writer']

Here we add a new organization.

>>> orgs['Zookd hOnc'] = org = Organization('Zookd hOnc')
>>> orgs['Zookd Devs'].parts.insert(registry.getId(org))
1
>>> org_catalog.index(orgs['Zookd hOnc'])
>>> org_catalog.index(orgs['Zookd Devs'])
>>> list(role_catalog.findValueTokens(
...     'role_id', t({'organization': orgs['Zookd hOnc'],
...                   'principal_id': 'abe'})))
['publisher', 'reviewer', 'user manager', 'writer']
>>> list(role_catalog.findValueTokens(
...     'role_id', t({'organization': orgs['Zookd hOnc'],
...                   'principal_id': 'ophelia'})))
['reviewer', 'writer']

Now we’ll remove it.

>>> orgs['Zookd Devs'].parts.remove(registry.getId(org))
>>> org_catalog.index(orgs['Zookd Devs'])
>>> org_catalog.unindex(orgs['Zookd hOnc'])

TODO make sure that intransitive copy looks the way we expect

[23]

Working with Search Indexes: zc.relation Catalog Extended Example

Introduction

This document assumes you have read the README.rst document, and want to learn a bit more by example. In it, we will explore a set of relations that demonstrates most of the aspects of working with search indexes and listeners. It will not explain the topics that the other documents already addressed. It also describes an advanced use case.

As we have seen in the other documents, the relation catalog supports search indexes. These can return the results of any search, as desired. Of course, the intent is that you supply an index that optimizes the particular searches it claims.

The searchindex module supplies a few search indexes, optimizing specified transitive and intransitive searches. We have seen them working in other documents. We will examine them more in depth in this document.

Search indexes update themselves by receiving messages via a “listener” interface. We will also look at how this works.

The example described in this file examines a use case similar to that in the zc.revision or zc.vault packages: a relation describes a graph of other objects. Therefore, this is our first concrete example of purely extrinsic relations.

Let’s build the example story a bit. Imagine we have a graph, often a hierarchy, of tokens–integers. Relations specify that a given integer token relates to other integer tokens, with a containment denotation or other meaning.

The integers may also have relations that specify that they represent an object or objects.

This allows us to have a graph of objects in which changing one part of the graph does not require changing the rest. zc.revision and zc.vault thus are able to model graphs that can have multiple revisions efficiently and with quite a bit of metadata to support merges.

Let’s imagine a simple hierarchy. The relation has a token attribute and a children attribute; children point to tokens. Relations will identify themselves with ids.

>>> import BTrees
>>> relations = BTrees.family64.IO.BTree()
>>> relations[99] = None # just to give us a start
>>> class Relation(object):
...     def __init__(self, token, children=()):
...         self.token = token
...         self.children = BTrees.family64.IF.TreeSet(children)
...         self.id = relations.maxKey() + 1
...         relations[self.id] = self
...
>>> def token(rel, self):
...     return rel.token
...
>>> def children(rel, self):
...     return rel.children
...
>>> def dumpRelation(obj, index, cache):
...     return obj.id
...
>>> def loadRelation(token, index, cache):
...     return relations[token]
...

The standard TransposingTransitiveQueriesFactory will be able to handle this quite well, so we’ll use that for our index.

>>> import zc.relation.queryfactory
>>> factory = zc.relation.queryfactory.TransposingTransitive(
...     'token', 'children')
>>> import zc.relation.catalog
>>> catalog = zc.relation.catalog.Catalog(
...     dumpRelation, loadRelation, BTrees.family64.IO, BTrees.family64)
>>> catalog.addValueIndex(token)
>>> catalog.addValueIndex(children, multiple=True)
>>> catalog.addDefaultQueryFactory(factory)

Now let’s quickly create a hierarchy and index it.

>>> for token, children in (
...     (0, (1, 2)), (1, (3, 4)), (2, (10, 11, 12)), (3, (5, 6)),
...     (4, (13, 14)), (5, (7, 8, 9)), (6, (15, 16)), (7, (17, 18, 19)),
...     (8, (20, 21, 22)), (9, (23, 24)), (10, (25, 26)),
...     (11, (27, 28, 29, 30, 31, 32))):
...     catalog.index(Relation(token, children))
...

[25] That hierarchy is arbitrary. Here’s what we have, in terms of tokens pointing to children:

                                 _____________0_____________
                                /                           \
                       ________1_______                ______2____________
                      /                \              /          |        \
               ______3_____            _4_          10       ____11_____   12
              /            \          /   \         / \     / /  |  \ \ \
      _______5_______       6       13     14     25  26  27 28 29 30 31 32
     /       |       \     / \
   _7_      _8_       9   15 16
  / | \    / | \     / \
17 18 19  20 21 22  23 24

Twelve relations, with tokens 0 through 11, and a total of 33 tokens, including children. The ids for the 12 relations are 100 through 111, corresponding with the tokens of 0 through 11.

Without a transitive search index, we can get all transitive results. The results are iterators.

>>> res = catalog.findRelationTokens({'token': 0})
>>> getattr(res, '__next__') is None
False
>>> getattr(res, '__len__', None) is None
True
>>> sorted(res)
[100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111]
>>> list(res)
[]
>>> res = catalog.findValueTokens('children', {'token': 0})
>>> sorted(res) == list(range(1, 33))
True
>>> list(res)
[]

[26] canFind also can work transitively, and will use transitive search indexes, as we’ll see below.

>>> catalog.canFind({'token': 1}, targetQuery={'children': 23})
True
>>> catalog.canFind({'token': 2}, targetQuery={'children': 23})
False
>>> catalog.canFind({'children': 23}, targetQuery={'token': 1})
True
>>> catalog.canFind({'children': 23}, targetQuery={'token': 2})
False

findRelationTokenChains won’t change, but we’ll include it in the discussion and examples to show that.

>>> res = catalog.findRelationTokenChains({'token': 2})
>>> chains = list(res)
>>> len(chains)
3
>>> len(list(res))
0

Transitive Search Indexes

Now we can add a couple of transitive search index. We’ll talk about them a bit first.

There is currently one variety of transitive index, which indexes relation and value searches for the transposing transitive query factory.

The index can only be used under certain conditions.

  • The search is not a request for a relation chain.

  • It does not specify a maximum depth.

  • Filters are not used.

If it is a value search, then specific value indexes cannot be used if a target filter or target query are used, but the basic relation index can still be used in that case.

The usage of the search indexes is largely transparent: set them up, and the relation catalog will use them for the same API calls that used more brute force previously. The only difference from external uses is that results that use an index will usually be a BTree structure, rather than an iterator.

When you add a transitive index for a relation, you must specify the transitive name (or names) of the query, and the same for the reverse. That’s all we’ll do now.

>>> import zc.relation.searchindex
>>> catalog.addSearchIndex(
...     zc.relation.searchindex.TransposingTransitiveMembership(
...         'token', 'children', names=('children',)))

Now we should have a search index installed.

Notice that we went from parent (token) to child: this index is primarily designed for helping transitive membership searches in a hierarchy. Using it to index parents would incur a lot of write expense for not much win.

There’s just a bit more you can specify here: static fields for a query to do a bit of filtering. We don’t need any of that for this example.

Now how does the catalog use this index for searches? Three basic ways, depending on the kind of search, relations, values, or canFind. Before we start looking into the internals, let’s verify that we’re getting what we expect: correct answers, and not iterators, but BTree structures.

>>> res = catalog.findRelationTokens({'token': 0})
>>> list(res)
[100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111]
>>> list(res)
[100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111]
>>> res = catalog.findValueTokens('children', {'token': 0})
>>> list(res) == list(range(1, 33))
True
>>> list(res) == list(range(1, 33))
True
>>> catalog.canFind({'token': 1}, targetQuery={'children': 23})
True
>>> catalog.canFind({'token': 2}, targetQuery={'children': 23})
False

[27] Note that the last two canFind examples from when we went through these examples without an index do not use the index, so we don’t show them here: they look the wrong direction for this index.

So how do these results happen?

The first, findRelationTokens, and the last, canFind, are the most straightforward. The index finds all relations that match the given query, intransitively. Then for each relation, it looks up the indexed transitive results for that token. The end result is the union of all indexed results found from the intransitive search. canFind simply casts the result into a boolean.

findValueTokens is the same story as above with only one more step. After the union of relations is calculated, the method returns the union of the sets of the requested value for all found relations.

It will maintain itself when relations are reindexed.

>>> rel = list(catalog.findRelations({'token': 11}))[0]
>>> for t in (27, 28, 29, 30, 31):
...     rel.children.remove(t)
...
>>> catalog.index(rel)
>>> catalog.findValueTokens('children', {'token': 0})
... # doctest: +NORMALIZE_WHITESPACE
LFSet([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
       20, 21, 22, 23, 24, 25, 26, 32])
>>> catalog.findValueTokens('children', {'token': 2})
LFSet([10, 11, 12, 25, 26, 32])
>>> catalog.findValueTokens('children', {'token': 11})
LFSet([32])
>>> rel.children.remove(32)
>>> catalog.index(rel)
>>> catalog.findValueTokens('children', {'token': 0})
... # doctest: +NORMALIZE_WHITESPACE
LFSet([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
       20, 21, 22, 23, 24, 25, 26])
>>> catalog.findValueTokens('children', {'token': 2})
LFSet([10, 11, 12, 25, 26])
>>> catalog.findValueTokens('children', {'token': 11})
LFSet([])
>>> rel.children.insert(27)
1
>>> catalog.index(rel)
>>> catalog.findValueTokens('children', {'token': 0})
... # doctest: +NORMALIZE_WHITESPACE
LFSet([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
       20, 21, 22, 23, 24, 25, 26, 27])
>>> catalog.findValueTokens('children', {'token': 2})
LFSet([10, 11, 12, 25, 26, 27])
>>> catalog.findValueTokens('children', {'token': 11})
LFSet([27])

When the index is copied, the search index is copied.

>>> new = catalog.copy()
>>> res = list(new.iterSearchIndexes())
>>> len(res)
1
>>> new_index = res[0]
>>> res = list(catalog.iterSearchIndexes())
>>> len(res)
1
>>> old_index = res[0]
>>> new_index is old_index
False
>>> old_index.index is new_index.index
False
>>> list(old_index.index.keys()) == list(new_index.index.keys())
True
>>> from __future__ import print_function
>>> for key, value in old_index.index.items():
...     v = new_index.index[key]
...     if v is value or list(v) != list(value):
...         print('oops', key, value, v)
...         break
... else:
...     print('good')
...
good
>>> old_index.names is not new_index.names
True
>>> list(old_index.names) == list(new_index.names)
True
>>> for name, old_ix in old_index.names.items():
...     new_ix = new_index.names[name]
...     if new_ix is old_ix or list(new_ix.keys()) != list(old_ix.keys()):
...         print('oops')
...         break
...     for key, value in old_ix.items():
...         v = new_ix[key]
...         if v is value or list(v) != list(value):
...             print('oops', name, key, value, v)
...             break
...     else:
...         continue
...     break
... else:
...     print('good')
...
good

Helpers

When writing search indexes and query factories, you often want complete access to relation catalog data. We’ve seen a number of these tools already:

  • getRelationModuleTools gets a dictionary of the BTree tools needed to work with relations.

    >>> sorted(catalog.getRelationModuleTools().keys())
    ... # doctest: +NORMALIZE_WHITESPACE
    ['BTree', 'Bucket', 'Set', 'TreeSet', 'difference', 'dump',
     'intersection', 'load', 'multiunion', 'union']
    

    ‘multiunion’ is only there if the BTree is an I* or L* module. Use the zc.relation.catalog.multiunion helper function to do the best union you can for a given set of tools.

  • getValueModuleTools does the same for indexed values.

    >>> tools = set(('BTree', 'Bucket', 'Set', 'TreeSet', 'difference',
    ...              'dump', 'intersection', 'load', 'multiunion', 'union'))
    >>> tools.difference(catalog.getValueModuleTools('children').keys()) == set()
    True
    
    >>> tools.difference(catalog.getValueModuleTools('token').keys()) == set()
    True
    
  • getRelationTokens can return all of the tokens in the catalog.

    >>> len(catalog.getRelationTokens()) == len(catalog)
    True
    

    This also happens to be equivalent to findRelationTokens with an empty query.

    >>> catalog.getRelationTokens() is catalog.findRelationTokens({})
    True
    

    It also can return all the tokens that match a given query, or None if there are no matches.

    >>> catalog.getRelationTokens({'token': 0}) # doctest: +ELLIPSIS
    <BTrees.LOBTree.LOTreeSet object at ...>
    >>> list(catalog.getRelationTokens({'token': 0}))
    [100]
    

    This also happens to be equivalent to findRelationTokens with a query, a maxDepth of 1, and no other arguments.

    >>> catalog.findRelationTokens({'token': 0}, maxDepth=1) is (
    ...     catalog.getRelationTokens({'token': 0}))
    True
    

    Except that if there are no matches, findRelationTokens returns an empty set (so it always returns an iterable).

    >>> catalog.findRelationTokens({'token': 50}, maxDepth=1)
    LOSet([])
    >>> print(catalog.getRelationTokens({'token': 50}))
    None
    
  • getValueTokens can return all of the tokens for a given value name in

    the catalog.

    >>> list(catalog.getValueTokens('token')) == list(range(12))
    True
    

    This is identical to catalog.findValueTokens with a name only (or with an empty query, and a maxDepth of 1).

    >>> list(catalog.findValueTokens('token')) == list(range(12))
    True
    >>> catalog.findValueTokens('token') is catalog.getValueTokens('token')
    True
    

    It can also return the values for a given token.

    >>> list(catalog.getValueTokens('children', 100))
    [1, 2]
    

    This is identical to catalog.findValueTokens with a name and a query of {None: token}.

    >>> list(catalog.findValueTokens('children', {None: 100}))
    [1, 2]
    >>> catalog.getValueTokens('children', 100) is (
    ...     catalog.findValueTokens('children', {None: 100}))
    True
    

    Except that if there are no matches, findValueTokens returns an empty set (so it always returns an iterable); while getValueTokens will return None if the relation has no values (or the relation is unknown).

    >>> catalog.findValueTokens('children', {None: 50}, maxDepth=1)
    LFSet([])
    >>> print(catalog.getValueTokens('children', 50))
    None
    
    >>> rel.children.remove(27)
    >>> catalog.index(rel)
    >>> catalog.findValueTokens('children', {None: rel.id}, maxDepth=1)
    LFSet([])
    >>> print(catalog.getValueTokens('children', rel.id))
    None
    
  • yieldRelationTokenChains is a search workhorse for searches that use a

    query factory. TODO: describe.

Optimizing Relation Catalog Use

There are several best practices and optimization opportunities in regards to the catalog.

  • Use integer-keyed BTree sets when possible. They can use the BTrees’ multiunion for a speed boost. Integers’ __cmp__ is reliable, and in C.

  • Never use persistent objects as keys. They will cause a database load every time you need to look at them, they take up memory and object caches, and they (as of this writing) disable conflict resolution. Intids (or similar) are your best bet for representing objects, and some other immutable such as strings are the next-best bet, and zope.app.keyreferences (or similar) are after that.

  • Use multiple-token values in your queries when possible, especially in your transitive query factories.

  • Use the cache when you are loading and dumping tokens, and in your transitive query factories.

  • When possible, don’t load or dump tokens (the values themselves may be used as tokens). This is especially important when you have multiple tokens: store them in a BTree structure in the same module as the zc.relation module for the value.

For some operations, particularly with hundreds or thousands of members in a single relation value, some of these optimizations can speed up some common-case reindexing work by around 100 times.

The easiest (and perhaps least useful) optimization is that all dump calls and all load calls generated by a single operation share a cache dictionary per call type (dump/load), per indexed relation value. Therefore, for instance, we could stash an intids utility, so that we only had to do a utility lookup once, and thereafter it was only a single dictionary lookup. This is what the default generateToken and resolveToken functions in zc.relationship’s index.py do: look at them for an example.

A further optimization is to not load or dump tokens at all, but use values that may be tokens. This will be particularly useful if the tokens have __cmp__ (or equivalent) in C, such as built-in types like ints. To specify this behavior, you create an index with the ‘load’ and ‘dump’ values for the indexed attribute descriptions explicitly set to None.

>>> import zope.interface
>>> class IRelation(zope.interface.Interface):
...     subjects = zope.interface.Attribute(
...         'The sources of the relation; the subject of the sentence')
...     relationtype = zope.interface.Attribute(
...         '''unicode: the single relation type of this relation;
...         usually contains the verb of the sentence.''')
...     objects = zope.interface.Attribute(
...         '''the targets of the relation; usually a direct or
...         indirect object in the sentence''')
...
>>> import BTrees
>>> relations = BTrees.family32.IO.BTree()
>>> relations[99] = None # just to give us a start
>>> @zope.interface.implementer(IRelation)
... class Relation(object):
...
...     def __init__(self, subjects, relationtype, objects):
...         self.subjects = subjects
...         assert relationtype in relTypes
...         self.relationtype = relationtype
...         self.objects = objects
...         self.id = relations.maxKey() + 1
...         relations[self.id] = self
...     def __repr__(self):
...         return '<%r %s %r>' % (
...             self.subjects, self.relationtype, self.objects)
>>> def token(rel, self):
...     return rel.token
...
>>> def children(rel, self):
...     return rel.children
...
>>> def dumpRelation(obj, index, cache):
...     return obj.id
...
>>> def loadRelation(token, index, cache):
...     return relations[token]
...
>>> relTypes = ['has the role of']
>>> def relTypeDump(obj, index, cache):
...     assert obj in relTypes, 'unknown relationtype'
...     return obj
...
>>> def relTypeLoad(token, index, cache):
...     assert token in relTypes, 'unknown relationtype'
...     return token
...
>>> import zc.relation.catalog
>>> catalog = zc.relation.catalog.Catalog(
...     dumpRelation, loadRelation)
>>> catalog.addValueIndex(IRelation['subjects'], multiple=True)
>>> catalog.addValueIndex(
...     IRelation['relationtype'], relTypeDump, relTypeLoad,
...     BTrees.family32.OI, name='reltype')
>>> catalog.addValueIndex(IRelation['objects'], multiple=True)
>>> import zc.relation.queryfactory
>>> factory = zc.relation.queryfactory.TransposingTransitive(
...     'subjects', 'objects')
>>> catalog.addDefaultQueryFactory(factory)
>>> rel = Relation((1,), 'has the role of', (2,))
>>> catalog.index(rel)
>>> list(catalog.findValueTokens('objects', {'subjects': 1}))
[2]

If you have single relations that relate hundreds or thousands of objects, it can be a huge win if the value is a ‘multiple’ of the same type as the stored BTree for the given attribute. The default BTree family for attributes is IFBTree; IOBTree is also a good choice, and may be preferrable for some applications.

>>> catalog.unindex(rel)
>>> rel = Relation(
...     BTrees.family32.IF.TreeSet((1,)), 'has the role of',
...     BTrees.family32.IF.TreeSet())
>>> catalog.index(rel)
>>> list(catalog.findValueTokens('objects', {'subjects': 1}))
[]
>>> list(catalog.findValueTokens('subjects', {'objects': None}))
[1]

Reindexing is where some of the big improvements can happen. The following gyrations exercise the optimization code.

>>> rel.objects.insert(2)
1
>>> catalog.index(rel)
>>> list(catalog.findValueTokens('objects', {'subjects': 1}))
[2]
>>> rel.subjects = BTrees.family32.IF.TreeSet((3,4,5))
>>> catalog.index(rel)
>>> list(catalog.findValueTokens('objects', {'subjects': 3}))
[2]
>>> rel.subjects.insert(6)
1
>>> catalog.index(rel)
>>> list(catalog.findValueTokens('objects', {'subjects': 6}))
[2]
>>> rel.subjects.update(range(100, 200))
100
>>> catalog.index(rel)
>>> list(catalog.findValueTokens('objects', {'subjects': 100}))
[2]
>>> rel.subjects = BTrees.family32.IF.TreeSet((3,4,5,6))
>>> catalog.index(rel)
>>> list(catalog.findValueTokens('objects', {'subjects': 3}))
[2]
>>> rel.subjects = BTrees.family32.IF.TreeSet(())
>>> catalog.index(rel)
>>> list(catalog.findValueTokens('objects', {'subjects': 3}))
[]
>>> rel.subjects = BTrees.family32.IF.TreeSet((3,4,5))
>>> catalog.index(rel)
>>> list(catalog.findValueTokens('objects', {'subjects': 3}))
[2]

tokenizeValues and resolveValueTokens work correctly without loaders and dumpers–that is, they do nothing.

>>> catalog.tokenizeValues((3,4,5), 'subjects')
(3, 4, 5)
>>> catalog.resolveValueTokens((3,4,5), 'subjects')
(3, 4, 5)

Changes

2.0 (2023-04-05)

  • Drop support for Python 2.7, 3.5, 3.6. [ale-rt]

  • Fix the dependency on the ZODB, we just need to depend on the BTrees package. Refs. #11. [ale-rt]

1.2 (2023-03-28)

1.1.post2 (2018-06-18)

  • Another attempt to fix PyPI page by using correct expected metadata syntax.

1.1.post1 (2018-06-18)

  • Fix PyPI page by using correct ReST syntax.

1.1 (2018-06-15)

  • Add support for Python 3.5 and 3.6.

1.0 (2008-04-23)

This is the initial release of the zc.relation package. However, it represents a refactoring of another package, zc.relationship. This package contains only a modified version of the relation(ship) index, now called a catalog. The refactored version of zc.relationship index relies on (subclasses) this catalog. zc.relationship also maintains a backwards-compatible subclass.

This package only relies on the ZODB, zope.interface, and zope.testing software, and can be used inside or outside of a standard ZODB database. The software does have to be there, though (the package relies heavily on the ZODB BTrees package).

If you would like to switch a legacy zc.relationship index to a zc.relation catalog, try this trick in your generations script. Assuming the old index is old, the following line should create a new zc.relation catalog with your legacy data:

>>> new = old.copy(zc.relation.Catalog)

Why is the same basic data structure called a catalog now? Because we exposed the ability to mutate the data structure, and what you are really adding and removing are indexes. It didn’t make sense to put an index in an index, but it does make sense to put an index in a catalog. Thus, a name change was born.

The catalog in this package has several incompatibilities from the earlier zc.relationship index, and many new features. The zc.relationship package maintains a backwards-compatible subclass. The following discussion compares the zc.relation catalog with the zc.relationship 1.x index.

Incompatibilities with zc.relationship 1.x index

The two big changes are that method names now refer to Relation rather than Relationship; and the catalog is instantiated slightly differently from the index. A few other changes are worth your attention. The following list attempts to highlight all incompatibilities.

Big incompatibilities:
  • findRelationshipTokenSet and findValueTokenSet are renamed, with some slightly different semantics, as getRelationTokens and getValueTokens. The exact same result as findRelationTokenSet(query) can be obtained with findRelationTokens(query, 1) (where 1 is maxDepth). The same result as findValueTokenSet(reltoken, name) can be obtained with findValueTokens(name, {zc.relation.RELATION: reltoken}, 1).

  • findRelations replaces findRelatonships. The new method will use the defaultTransitiveQueriesFactory if it is set and maxDepth is not 1. It shares the call signature of findRelationChains.

  • isLinked is now canFind.

  • The catalog instantiation arguments have changed from the old index.

    • load and dump (formerly loadRel and dumpRel, respectively) are now required arguments for instantiation.

    • The only other optional arguments are btree (was relFamily) and family. You now specify what elements to index with addValueIndex

    • Note also that addValueIndex defaults to no load and dump function, unlike the old instantiation options.

  • query factories are different. See IQueryFactory in the interfaces.

    • they first get (query, catalog, cache) and then return a getQueries callable that gets relchains and yields queries; OR None if they don’t match.

    • They must also handle an empty relchain. Typically this should return the original query, but may also be used to mutate the original query.

    • They are no longer thought of as transitive query factories, but as general query mutators.

Medium:
  • The catalog no longer inherits from zope.app.container.contained.Contained.

  • The index requires ZODB 3.8 or higher.

Small:
  • deactivateSets is no longer an instantiation option (it was broken because of a ZODB bug anyway, as had been described in the documentation).

Changes and new features

  • The catalog now offers the ability to index certain searches. The indexes must be explicitly instantiated and registered you want to optimize. This can be used when searching for values, when searching for relations, or when determining if two objects are linked. It cannot be used for relation chains. Requesting an index has the usual trade-offs of greater storage space and slower write speed for faster search speed. Registering a search index is done after instantiation time; you can iteratate over the current settings used, and remove them. (The code path expects to support legacy zc.relationship index instances for all of these APIs.)

  • You can now specify new values after the catalog has been created, iterate over the settings used, and remove values.

  • The catalog has a copy method, to quickly make new copies without actually having to reindex the relations.

  • query arguments can now specify multiple values for a given name by using zc.relation.catalog.any(1, 2, 3, 4) or zc.relation.catalog.Any((1, 2, 3, 4)).

  • The catalog supports specifying indexed values by passing callables rather than interface elements (which are also still supported).

  • findRelations and new method findRelationTokens can find relations transitively and intransitively. findRelationTokens when used intransitively repeats the legacy zc.relationship index behavior of findRelationTokenSet. (findRelationTokenSet remains in the API, not deprecated, a companion to findValueTokenSet.)

  • in findValues and findValueTokens, query argument is now optional. If the query evaluates to False in a boolean context, all values, or value tokens, are returned. Value tokens are explicitly returned using the underlying BTree storage. This can then be used directly for other BTree operations.

  • Completely new docs. Unfortunately, still really not good enough.

  • The package has drastically reduced direct dependecies from zc.relationship: it is now more clearly a ZODB tool, with no other Zope dependencies than zope.testing and zope.interface.

  • Listeners allow objects to listen to messages from the catalog (which can be used directly or, for instance, to fire off events).

  • You can search for relations, using a key of zc.relation.RELATION…which is really an alias for None. Sorry. But hey, use the constant! I think it is more readable.

  • tokenizeQuery (and resolveQuery) now accept keyword arguments as an alternative to a normal dict query. This can make constructing the query a bit more attractive (i.e., query = catalog.tokenizeQuery; res = catalog.findValues('object', query(subject=joe, predicate=OWNS))).

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

zc.relation-2.0.tar.gz (150.5 kB view hashes)

Uploaded Source

Built Distribution

zc.relation-2.0-py3-none-any.whl (111.7 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page