{ "info": { "author": "Gary Poster", "author_email": "gary@zope.com", "bugtrack_url": null, "classifiers": [ "License :: OSI Approved :: Zope Public License", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: Implementation :: CPython" ], "description": "================\nRelation Catalog\n================\n\n.. contents::\n\nOverview\n========\n\nThe relation catalog can be used to optimize intransitive and transitive\nsearches for N-ary relations of finite, preset dimensions.\n\nFor example, you can index simple two-way relations, like employee to\nsupervisor; RDF-style triples of subject-predicate-object; and more complex\nrelations such as subject-predicate-object with context and state. These\ncan be searched with variable definitions of transitive behavior.\n\nThe catalog can be used in the ZODB or standalone. It is a generic, relatively\npolicy-free tool.\n\nIt is expected to be used usually as an engine for more specialized and\nconstrained tools and APIs. Three such tools are zc.relationship containers,\nplone.relations containers, and zc.vault. The documents in the package,\nincluding this one, describe other possible uses.\n\nHistory\n=======\n\nThis is a refactoring of the ZODB-only parts of the zc.relationship package.\nSpecifically, the zc.relation catalog is largely equivalent to the\nzc.relationship index. The index in the zc.relationship 2.x line is an\nalmost-completely backwards-compatible wrapper of the zc.relation catalog.\nzc.relationship will continue to be maintained, though active development is\nexpected to go into zc.relation.\n\nMany of the ideas come from discussions with and code from Casey Duncan, Tres\nSeaver, Ken Manheimer, and more.\n\nSetting Up a Relation Catalog\n=============================\n\nIn this section, we will be introducing the following ideas.\n\n- Relations are objects with indexed values.\n\n- You add value indexes to relation catalogs to be able to search. Values\n can be identified to the catalog with callables or interface elements. The\n indexed value must be specified to the catalog as a single value or a\n collection.\n\n- Relations and their values are stored in the catalog as tokens: unique\n identifiers that you can resolve back to the original value. Integers are the\n most efficient tokens, but others can work fine too.\n\n- Token type determines the BTree module needed.\n\n- You must define your own functions for tokenizing and resolving tokens. These\n functions are registered with the catalog for the relations and for each of\n their value indexes.\n\n- Relations are indexed with ``index``.\n\nWe will use a simple two way relation as our example here. A brief introduction\nto a more complex RDF-style subject-predicate-object set up can be found later\nin the document.\n\nCreating the Catalog\n--------------------\n\nImagine a two way relation from one value to another. Let's say that we\nare modeling a relation of people to their supervisors: an employee may\nhave a single supervisor. For this first example, the relation between\nemployee and supervisor will be intrinsic: the employee has a pointer to\nthe supervisor, and the employee object itself represents the relation.\n\nLet's say further, for simplicity, that employee names are unique and\ncan be used to represent employees. We can use names as our \"tokens\".\n\nTokens are similar to the primary key in a relational database. A token is a\nway to identify an object. It must sort reliably and you must be able to write\na callable that reliably resolves to the object given the right context. In\nZope 3, intids (zope.app.intid) and keyreferences (zope.app.keyreference) are\ngood examples of reasonable tokens.\n\nAs we'll see below, you provide a way to convert objects to tokens, and resolve\ntokens to objects, for the relations, and for each value index individually.\nThey can be the all the same functions or completely different, depending on\nyour needs.\n\nFor speed, integers make the best tokens; followed by other\nimmutables like strings; followed by non-persistent objects; followed by\npersistent objects. The choice also determines a choice of BTree module, as\nwe'll see below.\n\nHere is our toy ``Employee`` example class. Again, we will use the employee\nname as the tokens.\n\n >>> employees = {} # we'll use this to resolve the \"name\" tokens\n >>> from functools import total_ordering\n >>> @total_ordering\n ... class Employee(object):\n ... def __init__(self, name, supervisor=None):\n ... if name in employees:\n ... raise ValueError('employee with same name already exists')\n ... self.name = name # expect this to be readonly\n ... self.supervisor = supervisor\n ... employees[name] = self\n ... # the next parts just make the tests prettier\n ... def __repr__(self):\n ... return ''\n ... def __lt__(self, other):\n ... return self.name < other.name\n ... def __eq__(self, other):\n ... return self is other\n ... def __hash__(self):\n ... ''' Dummy method needed because we defined __eq__\n ... '''\n ... return 1\n ...\n\nSo, we need to define how to turn employees into their tokens. We call the\ntokenization a \"dump\" function. Conversely, the function to resolve tokens into\nobjects is called a \"load\".\n\nFunctions to dump relations and values get several arguments. The first\nargument is the object to be tokenized. Next, because it helps sometimes to\nprovide context, is the catalog. The last argument is a dictionary that will be\nshared for a given search. The dictionary can be ignored, or used as a cache\nfor optimizations (for instance, to stash a utility that you looked up).\n\nFor this example, our function is trivial: we said the token would be\nthe employee's name.\n\n >>> def dumpEmployees(emp, catalog, cache):\n ... return emp.name\n ...\n\nIf you store the relation catalog persistently (e.g., in the ZODB) be aware\nthat the callables you provide must be picklable--a module-level function,\nfor instance.\n\nWe also need a way to turn tokens into employees, or \"load\".\n\nThe \"load\" functions get the token to be resolved; the catalog, for\ncontext; and a dict cache, for optimizations of subsequent calls.\n\nYou might have noticed in our ``Employee.__init__`` that we keep a mapping\nof name to object in the ``employees`` global dict (defined right above\nthe class definition). We'll use that for resolving the tokens.\n\n >>> def loadEmployees(token, catalog, cache):\n ... return employees[token]\n ...\n\nNow we know enough to get started with a catalog. We'll instantiate it\nby specifying how to tokenize relations, and what kind of BTree modules\nshould be used to hold the tokens.\n\nHow do you pick BTree modules?\n\n- If the tokens are 32-bit ints, choose ``BTrees.family32.II``,\n ``BTrees.family32.IF`` or ``BTrees.family32.IO``.\n\n- If the tokens are 64 bit ints, choose ``BTrees.family64.II``,\n ``BTrees.family64.IF`` or ``BTrees.family64.IO``.\n\n- If they are anything else, choose ``BTrees.family32.OI``,\n ``BTrees.family64.OI``, or ``BTrees.family32.OO`` (or\n ``BTrees.family64.OO``--they are the same).\n\nWithin these rules, the choice is somewhat arbitrary unless you plan to merge\nthese results with that of another source that is using a particular BTree\nmodule. BTree set operations only work within the same module, so you must\nmatch module to module. The catalog defaults to IF trees, because that's what\nstandard zope catalogs use. That's as reasonable a choice as any, and will\npotentially come in handy if your tokens are in fact the same as those used by\nthe zope catalog and you want to do some set operations.\n\nIn this example, our tokens are strings, so we want OO or an OI variant. We'll\nchoose BTrees.family32.OI, arbitrarily.\n\n >>> import zc.relation.catalog\n >>> import BTrees\n >>> catalog = zc.relation.catalog.Catalog(dumpEmployees, loadEmployees,\n ... btree=BTrees.family32.OI)\n\n[#verifyObjectICatalog]_\n\n.. [#verifyObjectICatalog] The catalog provides ICatalog.\n\n >>> from zope.interface.verify import verifyObject\n >>> import zc.relation.interfaces\n >>> verifyObject(zc.relation.interfaces.ICatalog, catalog)\n True\n\n[#legacy]_\n\n\n.. [#legacy] Old instances of zc.relationship indexes, which in the newest\n version subclass a zc.relation Catalog, used to have a dict in an\n internal data structure. We specify that here so that the code that\n converts the dict to an OOBTree can have a chance to run.\n\n >>> catalog._attrs = dict(catalog._attrs)\n\nLook! A relation catalog! We can't do very\nmuch searching with it so far though, because the catalog doesn't have any\nindexes.\n\nIn this example, the relation itself represents the employee, so we won't need\nto index that separately.\n\nBut we do need a way to tell the catalog how to find the other end of the\nrelation, the supervisor. You can specify this to the catalog with an attribute\nor method specified from ``zope.interface Interface``, or with a callable.\nWe'll use a callable for now. The callable will receive the indexed relation\nand the catalog for context.\n\n >>> def supervisor(emp, catalog):\n ... return emp.supervisor # None or another employee\n ...\n\nWe'll also need to specify how to tokenize (dump and load) those values. In\nthis case, we're able to use the same functions as the relations themselves.\nHowever, do note that we can specify a completely different way to dump and\nload for each \"value index,\" or relation element.\n\nWe could also specify the name to call the index, but it will default to the\n``__name__`` of the function (or interface element), which will work just fine\nfor us now.\n\nNow we can add the \"supervisor\" value index.\n\n >>> catalog.addValueIndex(supervisor, dumpEmployees, loadEmployees,\n ... btree=BTrees.family32.OI)\n\nNow we have an index [#addValueIndexExceptions]_.\n\n.. [#addValueIndexExceptions] Adding a value index can generate several\n exceptions.\n\n You must supply both of dump and load or neither.\n\n >>> catalog.addValueIndex(supervisor, dumpEmployees, None,\n ... btree=BTrees.family32.OI, name='supervisor2')\n Traceback (most recent call last):\n ...\n ValueError: either both of 'dump' and 'load' must be None, or neither\n\n In this example, even if we fix it, we'll get an error, because we have\n already indexed the supervisor function.\n\n >>> catalog.addValueIndex(supervisor, dumpEmployees, loadEmployees,\n ... btree=BTrees.family32.OI, name='supervisor2')\n ... # doctest: +ELLIPSIS\n Traceback (most recent call last):\n ...\n ValueError: ('element already indexed', )\n\n You also can't add a different function under the same name.\n\n >>> def supervisor2(emp, catalog):\n ... return emp.supervisor # None or another employee\n ...\n >>> catalog.addValueIndex(supervisor2, dumpEmployees, loadEmployees,\n ... btree=BTrees.family32.OI, name='supervisor')\n ... # doctest: +ELLIPSIS\n Traceback (most recent call last):\n ...\n ValueError: ('name already used', 'supervisor')\n\n Finally, if your function does not have a ``__name__`` and you do not\n provide one, you may not add an index.\n\n >>> class Supervisor3(object):\n ... __name__ = None\n ... def __call__(klass, emp, catalog):\n ... return emp.supervisor\n ...\n >>> supervisor3 = Supervisor3()\n >>> supervisor3.__name__\n >>> catalog.addValueIndex(supervisor3, dumpEmployees, loadEmployees,\n ... btree=BTrees.family32.OI)\n ... # doctest: +ELLIPSIS\n Traceback (most recent call last):\n ...\n ValueError: no name specified\n\n >>> [info['name'] for info in catalog.iterValueIndexInfo()]\n ['supervisor']\n\nAdding Relations\n----------------\n\nNow let's create a few employees. All but one will have supervisors.\nIf you recall our toy ``Employee`` class, the first argument to the\nconstructor is the employee name (and therefore the token), and the\noptional second argument is the supervisor.\n\n >>> a = Employee('Alice')\n >>> b = Employee('Betty', a)\n >>> c = Employee('Chuck', a)\n >>> d = Employee('Diane', b)\n >>> e = Employee('Edgar', b)\n >>> f = Employee('Frank', c)\n >>> g = Employee('Galyn', c)\n >>> h = Employee('Howie', d)\n\nHere is a diagram of the hierarchy.\n\n::\n\n Alice\n __/ \\__\n Betty Chuck\n / \\ / \\\n Diane Edgar Frank Galyn\n |\n Howie\n\nLet's tell the catalog about the relations, using the ``index`` method.\n\n >>> for emp in (a,b,c,d,e,f,g,h):\n ... catalog.index(emp)\n ...\n\nWe've now created the relation catalog and added relations to it. We're ready\nto search!\n\nSearching\n=========\n\nIn this section, we will introduce the following ideas.\n\n- Queries to the relation catalog are formed with dicts.\n\n- Query keys are the names of the indexes you want to search, or, for the\n special case of precise relations, the ``zc.relation.RELATION`` constant.\n\n- Query values are the tokens of the results you want to match; or ``None``,\n indicating relations that have ``None`` as a value (or an empty collection,\n if it is a multiple). Search values can use\n ``zc.relation.catalog.any(args)`` or ``zc.relation.catalog.Any(args)`` to\n specify multiple (non-``None``) results to match for a given key.\n\n- The index has a variety of methods to help you work with tokens.\n ``tokenizeQuery`` is typically the most used, though others are available.\n\n- To find relations that match a query, use ``findRelations`` or\n ``findRelationTokens``.\n\n- To find values that match a query, use ``findValues`` or ``findValueTokens``.\n\n- You search transitively by using a query factory. The\n ``zc.relation.queryfactory.TransposingTransitive`` is a good common case\n factory that lets you walk up and down a hierarchy. A query factory can be\n passed in as an argument to search methods as a ``queryFactory``, or\n installed as a default behavior using ``addDefaultQueryFactory``.\n\n- To find how a query is related, use ``findRelationChains`` or\n ``findRelationTokenChains``.\n\n- To find out if a query is related, use ``canFind``.\n\n- Circular transitive relations are handled to prevent infinite loops. They\n are identified in ``findRelationChains`` and ``findRelationTokenChains`` with\n a ``zc.relation.interfaces.ICircularRelationPath`` marker interface.\n\n- search methods share the following arguments:\n\n * ``maxDepth``, limiting the transitive depth for searches;\n\n * ``filter``, allowing code to filter transitive paths;\n\n * ``targetQuery``, allowing a query to filter transitive paths on the basis\n of the endpoint;\n\n * ``targetFilter``, allowing code to filter transitive paths on the basis of\n the endpoint; and\n\n * ``queryFactory``, mentioned above.\n\n- You can set up search indexes to speed up specific transitive searches.\n\nQueries, ``findRelations``, and special query values\n----------------------------------------------------\n\nSo who works for Alice? That means we want to get the relations--the\nemployees--with a ``supervisor`` of Alice.\n\nThe heart of a question to the catalog is a query. A query is spelled\nas a dictionary. The main idea is simply that keys in a dictionary\nspecify index names, and the values specify the constraints.\n\nThe values in a query are always expressed with tokens. The catalog has\nseveral helpers to make this less onerous, but for now let's take\nadvantage of the fact that our tokens are easily comprehensible.\n\n >>> sorted(catalog.findRelations({'supervisor': 'Alice'}))\n [, ]\n\nAlice is the direct (intransitive) boss of Betty and Chuck.\n\nWhat if you want to ask \"who doesn't report to anyone?\" Then you want to\nask for a relation in which the supervisor is None.\n\n >>> list(catalog.findRelations({'supervisor': None}))\n []\n\nAlice is the only employee who doesn't report to anyone.\n\nWhat if you want to ask \"who reports to Diane or Chuck?\" Then you use the\nzc.relation ``Any`` class or ``any`` function to pass the multiple values.\n\n >>> sorted(catalog.findRelations(\n ... {'supervisor': zc.relation.catalog.any('Diane', 'Chuck')}))\n ... # doctest: +NORMALIZE_WHITESPACE\n [, ,\n ]\n\nFrank, Galyn, and Howie each report to either Diane or Chuck. [#any]_\n\n.. [#any] ``Any`` can be compared.\n\n >>> zc.relation.catalog.any('foo', 'bar', 'baz')\n \n >>> (zc.relation.catalog.any('foo', 'bar', 'baz') ==\n ... zc.relation.catalog.any('bar', 'foo', 'baz'))\n True\n >>> (zc.relation.catalog.any('foo', 'bar', 'baz') !=\n ... zc.relation.catalog.any('bar', 'foo', 'baz'))\n False\n >>> (zc.relation.catalog.any('foo', 'bar', 'baz') ==\n ... zc.relation.catalog.any('foo', 'baz'))\n False\n >>> (zc.relation.catalog.any('foo', 'bar', 'baz') !=\n ... zc.relation.catalog.any('foo', 'baz'))\n True\n\n\n\n``findValues`` and the ``RELATION`` query key\n---------------------------------------------\n\nSo how do we find who an employee's supervisor is? Well, in this case,\nlook at the attribute on the employee! If you can use an attribute that\nwill usually be a win in the ZODB.\n\n >>> h.supervisor\n \n\nAgain, as we mentioned at the start of this first example, the knowledge\nof a supervisor is \"intrinsic\" to the employee instance. It is\npossible, and even easy, to ask the catalog this kind of question, but\nthe catalog syntax is more geared to \"extrinsic\" relations, such as the\none from the supervisor to the employee: the connection between a\nsupervisor object and its employees is extrinsic to the supervisor, so\nyou actually might want a catalog to find it!\n\nHowever, we will explore the syntax very briefly, because it introduces an\nimportant pair of search methods, and because it is a stepping stone\nto our first transitive search.\n\nSo, o relation catalog, who is Howie's supervisor?\n\nTo ask this question we want to get the indexed values off of the relations:\n``findValues``. In its simplest form, the arguments are the index name of the\nvalues you want, and a query to find the relations that have the desired\nvalues.\n\nWhat about the query? Above, we noted that the keys in a query are the names of\nthe indexes to search. However, in this case, we don't want to search one or\nmore indexes for matching relations, as usual, but actually specify a relation:\nHowie.\n\nWe do not have a value index name: we are looking for a relation. The query\nkey, then, should be the constant ``zc.relation.RELATION``. For our current\nexample, that would mean the query is ``{zc.relation.RELATION: 'Howie'}``.\n\n >>> import zc.relation\n >>> list(catalog.findValues(\n ... 'supervisor', {zc.relation.RELATION: 'Howie'}))[0]\n \n\nCongratulations, you just found an obfuscated and comparitively\ninefficient way to write ``howie.supervisor``! [#intrinsic_search]_\n\n.. [#intrinsic_search] Here's the same with token results.\n\n >>> list(catalog.findValueTokens('supervisor',\n ... {zc.relation.RELATION: 'Howie'}))\n ['Diane']\n\n While we're down here in the footnotes, I'll mention that you can\n search for relations that haven't been indexed.\n\n >>> list(catalog.findRelationTokens({zc.relation.RELATION: 'Ygritte'}))\n []\n >>> list(catalog.findRelations({zc.relation.RELATION: 'Ygritte'}))\n []\n\n[#findValuesExceptions]_\n\n\n.. [#findValuesExceptions] If you use ``findValues`` or ``findValueTokens`` and\n try to specify a value name that is not indexed, you get a ValueError.\n\n >>> catalog.findValues('foo')\n Traceback (most recent call last):\n ...\n ValueError: ('name not indexed', 'foo')\n\n\nSlightly more usefully, you can use other query keys along with\nzc.relation.RELATION. This asks, \"Of Betty, Alice, and Frank, who are\nsupervised by Alice?\"\n\n >>> sorted(catalog.findRelations(\n ... {zc.relation.RELATION: zc.relation.catalog.any(\n ... 'Betty', 'Alice', 'Frank'),\n ... 'supervisor': 'Alice'}))\n []\n\nOnly Betty is.\n\nTokens\n------\n\nAs mentioned above, the catalog provides several helpers to work with tokens.\nThe most frequently used is ``tokenizeQuery``, which takes a query with object\nvalues and converts them to tokens using the \"dump\" functions registered for\nthe relations and indexed values. Here are alternate spellings of some of the\nqueries we've encountered above.\n\n >>> catalog.tokenizeQuery({'supervisor': a})\n {'supervisor': 'Alice'}\n >>> catalog.tokenizeQuery({'supervisor': None})\n {'supervisor': None}\n >>> import pprint\n >>> result = catalog.tokenizeQuery(\n ... {zc.relation.RELATION: zc.relation.catalog.any(a, b, f),\n ... 'supervisor': a}) # doctest: +NORMALIZE_WHITESPACE\n >>> pprint.pprint(result)\n {None: ,\n 'supervisor': 'Alice'}\n\n(If you are wondering about that ``None`` in the last result, yes,\n``zc.relation.RELATION`` is just readability sugar for ``None``.)\n\nSo, here's a real search using ``tokenizeQuery``. We'll make an alias for\n``catalog.tokenizeQuery`` just to shorten things up a bit.\n\n >>> query = catalog.tokenizeQuery\n >>> sorted(catalog.findRelations(query(\n ... {zc.relation.RELATION: zc.relation.catalog.any(a, b, f),\n ... 'supervisor': a})))\n []\n\nThe catalog always has parallel search methods, one for finding objects, as\nseen above, and one for finding tokens (the only exception is ``canFind``,\ndescribed below). Finding tokens can be much more efficient, especially if the\nresult from the relation catalog is just one step along the path of finding\nyour desired result. But finding objects is simpler for some common cases.\nHere's a quick example of some queries above, getting tokens rather than\nobjects.\n\nYou can also spell a query in ``tokenizeQuery`` with keyword arguments. This\nwon't work if your key is ``zc.relation.RELATION``, but otherwise it can\nimprove readability. We'll see some examples of this below as well.\n\n >>> sorted(catalog.findRelationTokens(query(supervisor=a)))\n ['Betty', 'Chuck']\n\n >>> sorted(catalog.findRelationTokens({'supervisor': None}))\n ['Alice']\n\n >>> sorted(catalog.findRelationTokens(\n ... query(supervisor=zc.relation.catalog.any(c, d))))\n ['Frank', 'Galyn', 'Howie']\n\n >>> sorted(catalog.findRelationTokens(\n ... query({zc.relation.RELATION: zc.relation.catalog.any(a, b, f),\n ... 'supervisor': a})))\n ['Betty']\n\nThe catalog provides several other methods just for working with tokens.\n\n- ``resolveQuery``: the inverse of ``tokenizeQuery``, converting a\n tokenizedquery to a query with objects.\n\n- ``tokenizeValues``: returns an iterable of tokens for the values of the given\n index name.\n\n- ``resolveValueTokens``: returns an iterable of values for the tokens of the\n given index name.\n\n- ``tokenizeRelation``: returns a token for the given relation.\n\n- ``resolveRelationToken``: returns a relation for the given token.\n\n- ``tokenizeRelations``: returns an iterable of tokens for the relations given.\n\n- ``resolveRelationTokens``: returns an iterable of relations for the tokens\n given.\n\nThese methods are lesser used, and described in more technical documents in\nthis package.\n\nTransitive Searching, Query Factories, and ``maxDepth``\n-------------------------------------------------------\n\nSo, we've seen a lot of one-level, intransitive searching. What about\ntransitive searching? Well, you need to tell the catalog how to walk the tree.\nIn simple (and very common) cases like this, the\n``zc.relation.queryfactory.TransposingTransitive`` will do the trick.\n\nA transitive query factory is just a callable that the catalog uses to\nask \"I got this query, and here are the results I found. I'm supposed to\nwalk another step transitively, so what query should I search for next?\"\nWriting a factory is more complex than we want to talk about right now,\nbut using the ``TransposingTransitiveQueryFactory`` is easy. You just tell\nit the two query names it should transpose for walking in either\ndirection.\n\nFor instance, here we just want to tell the factory to transpose the two keys\nwe've used, ``zc.relation.RELATION`` and 'supervisor'. Let's make a factory,\nuse it in a query for a couple of transitive searches, and then, if you want,\nyou can read through a footnote to talk through what is happening.\n\nHere's the factory.\n\n >>> import zc.relation.queryfactory\n >>> factory = zc.relation.queryfactory.TransposingTransitive(\n ... zc.relation.RELATION, 'supervisor')\n\nNow ``factory`` is just a callable. Let's let it help answer a couple of\nquestions.\n\nWho are all of Howie's supervisors transitively (this looks up in the\ndiagram)?\n\n >>> list(catalog.findValues('supervisor', {zc.relation.RELATION: 'Howie'},\n ... queryFactory=factory))\n ... # doctest: +NORMALIZE_WHITESPACE\n [, ,\n ]\n\nWho are all of the people Betty supervises transitively, breadth first (this\nlooks down in the diagram)?\n\n >>> people = list(catalog.findRelations(\n ... {'supervisor': 'Betty'}, queryFactory=factory))\n >>> sorted(people[:2])\n [, ]\n >>> people[2]\n \n\nYup, that looks right. So how did that work? If you care, read this\nfootnote. [#I_care]_\n\nThis transitive factory is really the only transitive factory you would\nwant for this particular catalog, so it probably is safe to wire it in\nas a default. You can add multiple query factories to match different\nqueries using ``addDefaultQueryFactory``.\n\n >>> catalog.addDefaultQueryFactory(factory)\n\nNow all searches are transitive by default.\n\n >>> list(catalog.findValues('supervisor', {zc.relation.RELATION: 'Howie'}))\n ... # doctest: +NORMALIZE_WHITESPACE\n [, ,\n ]\n >>> people = list(catalog.findRelations({'supervisor': 'Betty'}))\n >>> sorted(people[:2])\n [, ]\n >>> people[2]\n \n\nWe can force a non-transitive search, or a specific search depth, with\n``maxDepth`` [#needs_a_transitive_queries_factory]_.\n\n\n.. [#needs_a_transitive_queries_factory] A search with a ``maxDepth`` > 1 but\n no ``queryFactory`` raises an error.\n\n >>> catalog.removeDefaultQueryFactory(factory)\n >>> catalog.findRelationTokens({'supervisor': 'Diane'}, maxDepth=3)\n Traceback (most recent call last):\n ...\n ValueError: if maxDepth not in (None, 1), queryFactory must be available\n\n >>> catalog.addDefaultQueryFactory(factory)\n\n >>> list(catalog.findValues(\n ... 'supervisor', {zc.relation.RELATION: 'Howie'}, maxDepth=1))\n []\n >>> sorted(catalog.findRelations({'supervisor': 'Betty'}, maxDepth=1))\n [, ]\n\n[#maxDepthExceptions]_\n\n\n.. [#maxDepthExceptions] ``maxDepth`` must be None or a positive integer, or\n else you'll get a value error.\n\n >>> catalog.findRelations({'supervisor': 'Betty'}, maxDepth=0)\n Traceback (most recent call last):\n ...\n ValueError: maxDepth must be None or a positive integer\n\n >>> catalog.findRelations({'supervisor': 'Betty'}, maxDepth=-1)\n Traceback (most recent call last):\n ...\n ValueError: maxDepth must be None or a positive integer\n\nWe'll introduce some other available search\narguments later in this document and in other documents. It's important\nto note that *all search methods share the same arguments as\n``findRelations``*. ``findValues`` and ``findValueTokens`` only add the\ninitial argument of specifying the desired value.\n\nWe've looked at two search methods so far: the ``findValues`` and\n``findRelations`` methods help you ask what is related. But what if you\nwant to know *how* things are transitively related?\n\n``findRelationChains`` and ``targetQuery``\n------------------------------------------\n\nAnother search method, ``findRelationChains``, helps you discover how\nthings are transitively related.\n\nThe method name says \"find relation chains\". But what is a \"relation\nchain\"? In this API, it is a transitive path of relations. For\ninstance, what's the chain of command above Howie? ``findRelationChains``\nwill return each unique path.\n\n >>> list(catalog.findRelationChains({zc.relation.RELATION: 'Howie'}))\n ... # doctest: +NORMALIZE_WHITESPACE\n [(,),\n (, ),\n (, ,\n ),\n (, ,\n , )]\n\nLook at that result carefully. Notice that the result is an iterable of\ntuples. Each tuple is a unique chain, which may be a part of a\nsubsequent chain. In this case, the last chain is the longest and the\nmost comprehensive.\n\nWhat if we wanted to see all the paths from Alice? That will be one\nchain for each supervised employee, because it shows all possible paths.\n\n >>> sorted(catalog.findRelationChains(\n ... {'supervisor': 'Alice'}))\n ... # doctest: +NORMALIZE_WHITESPACE\n [(,),\n (, ),\n (, ,\n ),\n (, ),\n (,),\n (, ),\n (, )]\n\nThat's all the paths--all the chains--from Alice. We sorted the results,\nbut normally they would be breadth first.\n\nBut what if we wanted to just find the paths from one query result to\nanother query result--say, we wanted to know the chain of command from Alice\ndown to Howie? Then we can specify a ``targetQuery`` that specifies the\ncharacteristics of our desired end point (or points).\n\n >>> list(catalog.findRelationChains(\n ... {'supervisor': 'Alice'},\n ... targetQuery={zc.relation.RELATION: 'Howie'}))\n ... # doctest: +NORMALIZE_WHITESPACE\n [(, ,\n )]\n\nSo, Betty supervises Diane, who supervises Howie.\n\nNote that ``targetQuery`` now joins ``maxDepth`` in our collection of shared\nsearch arguments that we have introduced.\n\n``filter`` and ``targetFilter``\n-------------------------------\n\nWe can take a quick look now at the last of the two shared search arguments:\n``filter`` and ``targetFilter``. These two are similar in that they both are\ncallables that can approve or reject given relations in a search based on\nwhatever logic you can code. They differ in that ``filter`` stops any further\ntransitive searches from the relation, while ``targetFilter`` merely omits the\ngiven result but allows further search from it. Like ``targetQuery``, then,\n``targetFilter`` is good when you want to specify the other end of a path.\n\nAs an example, let's say we only want to return female employees.\n\n >>> female_employees = ('Alice', 'Betty', 'Diane', 'Galyn')\n >>> def female_filter(relchain, query, catalog, cache):\n ... return relchain[-1] in female_employees\n ...\n\nHere are all the female employees supervised by Alice transitively, using\n``targetFilter``.\n\n >>> list(catalog.findRelations({'supervisor': 'Alice'},\n ... targetFilter=female_filter))\n ... # doctest: +NORMALIZE_WHITESPACE\n [, ,\n ]\n\nHere are all the female employees supervised by Chuck.\n\n >>> list(catalog.findRelations({'supervisor': 'Chuck'},\n ... targetFilter=female_filter))\n []\n\nThe same method used as a filter will only return females directly\nsupervised by other females--not Galyn, in this case.\n\n >>> list(catalog.findRelations({'supervisor': 'Alice'},\n ... filter=female_filter))\n [, ]\n\nThese can be combined with one another, and with the other search\narguments [#filter]_.\n\n.. [#filter] For instance:\n\n >>> list(catalog.findRelationTokens(\n ... {'supervisor': 'Alice'}, targetFilter=female_filter,\n ... targetQuery={zc.relation.RELATION: 'Galyn'}))\n ['Galyn']\n >>> list(catalog.findRelationTokens(\n ... {'supervisor': 'Alice'}, targetFilter=female_filter,\n ... targetQuery={zc.relation.RELATION: 'Not known'}))\n []\n >>> arbitrary = ['Alice', 'Chuck', 'Betty', 'Galyn']\n >>> def arbitrary_filter(relchain, query, catalog, cache):\n ... return relchain[-1] in arbitrary\n >>> list(catalog.findRelationTokens({'supervisor': 'Alice'},\n ... filter=arbitrary_filter,\n ... targetFilter=female_filter))\n ['Betty', 'Galyn']\n\nSearch indexes\n--------------\n\nWithout setting up any additional indexes, the transitive behavior of\nthe ``findRelations`` and ``findValues`` methods essentially relies on the\nbrute force searches of ``findRelationChains``. Results are iterables\nthat are gradually computed. For instance, let's repeat the question\n\"Whom does Betty supervise?\". Notice that ``res`` first populates a list\nwith three members, but then does not populate a second list. The\niterator has been exhausted.\n\n >>> res = catalog.findRelationTokens({'supervisor': 'Betty'})\n >>> unindexed = sorted(res)\n >>> len(unindexed)\n 3\n >>> len(list(res)) # iterator is exhausted\n 0\n\nThe brute force of this approach can be sufficient in many cases, but\nsometimes speed for these searches is critical. In these cases, you can\nadd a \"search index\". A search index speeds up the result of one or\nmore precise searches by indexing the results. Search indexes can\naffect the results of searches with a ``queryFactory`` in ``findRelations``,\n``findValues``, and the soon-to-be-introduced ``canFind``, but they do not\naffect ``findRelationChains``.\n\nThe zc.relation package currently includes two kinds of search indexes, one for\nindexing transitive membership searches in a hierarchy and one for intransitive\nsearches explored in tokens.rst in this package, which can optimize frequent\nsearches on complex queries or can effectively change the meaning of an\nintransitive search. Other search index implementations and approaches may be\nadded in the future.\n\nHere's a very brief example of adding a search index for the transitive\nsearches seen above that specify a 'supervisor'.\n\n >>> import zc.relation.searchindex\n >>> catalog.addSearchIndex(\n ... zc.relation.searchindex.TransposingTransitiveMembership(\n ... 'supervisor', zc.relation.RELATION))\n\nThe ``zc.relation.RELATION`` describes how to walk back up the chain. Search\nindexes are explained in reasonable detail in searchindex.rst.\n\nNow that we have added the index, we can search again. The result this\ntime is already computed, so, at least when you ask for tokens, it\nis repeatable.\n\n >>> res = catalog.findRelationTokens({'supervisor': 'Betty'})\n >>> len(list(res))\n 3\n >>> len(list(res))\n 3\n >>> sorted(res) == unindexed\n True\n\nNote that the breadth-first sorting is lost when an index is used [#updates]_.\n\n.. [#updates] The scenario we are looking at in this document shows a case\n in which special logic in the search index needs to address updates.\n For example, if we move Howie from Diane\n\n ::\n\n Alice\n __/ \\__\n Betty Chuck\n / \\ / \\\n Diane Edgar Frank Galyn\n |\n Howie\n\n to Galyn\n\n ::\n\n Alice\n __/ \\__\n Betty Chuck\n / \\ / \\\n Diane Edgar Frank Galyn\n |\n Howie\n\n then the search index is correct both for the new location and the old.\n\n >>> h.supervisor = g\n >>> catalog.index(h)\n >>> list(catalog.findRelationTokens({'supervisor': 'Diane'}))\n []\n >>> list(catalog.findRelationTokens({'supervisor': 'Betty'}))\n ['Diane', 'Edgar']\n >>> list(catalog.findRelationTokens({'supervisor': 'Chuck'}))\n ['Frank', 'Galyn', 'Howie']\n >>> list(catalog.findRelationTokens({'supervisor': 'Galyn'}))\n ['Howie']\n >>> h.supervisor = d\n >>> catalog.index(h) # move him back\n >>> list(catalog.findRelationTokens({'supervisor': 'Galyn'}))\n []\n >>> list(catalog.findRelationTokens({'supervisor': 'Diane'}))\n ['Howie']\n\nTransitive cycles (and updating and removing relations)\n-------------------------------------------------------\n\nThe transitive searches and the provided search indexes can handle\ncycles. Cycles are less likely in the current example than some others,\nbut we can stretch the case a bit: imagine a \"king in disguise\", in\nwhich someone at the top works lower in the hierarchy. Perhaps Alice\nworks for Zane, who works for Betty, who works for Alice. Artificial,\nbut easy enough to draw::\n\n ______\n / \\\n / Zane\n / |\n / Alice\n / __/ \\__\n / Betty__ Chuck\n \\-/ / \\ / \\\n Diane Edgar Frank Galyn\n |\n Howie\n\nEasy to create too.\n\n >>> z = Employee('Zane', b)\n >>> a.supervisor = z\n\nNow we have a cycle. Of course, we have not yet told the catalog about it.\n``index`` can be used both to reindex Alice and index Zane.\n\n >>> catalog.index(a)\n >>> catalog.index(z)\n\nNow, if we ask who works for Betty, we get the entire tree. (We'll ask\nfor tokens, just so that the result is smaller to look at.) [#same_set]_\n\n.. [#same_set] The result of the query for Betty, Alice, and Zane are all the\n same.\n\n >>> res1 = catalog.findRelationTokens({'supervisor': 'Betty'})\n >>> res2 = catalog.findRelationTokens({'supervisor': 'Alice'})\n >>> res3 = catalog.findRelationTokens({'supervisor': 'Zane'})\n >>> list(res1) == list(res2) == list(res3)\n True\n\n The cycle doesn't pollute the index outside of the cycle.\n\n >>> res = catalog.findRelationTokens({'supervisor': 'Diane'})\n >>> list(res)\n ['Howie']\n >>> list(res) # it isn't lazy, it is precalculated\n ['Howie']\n\n >>> sorted(catalog.findRelationTokens({'supervisor': 'Betty'}))\n ... # doctest: +NORMALIZE_WHITESPACE\n ['Alice', 'Betty', 'Chuck', 'Diane', 'Edgar', 'Frank', 'Galyn', 'Howie',\n 'Zane']\n\nIf we ask for the supervisors of Frank, it will include Betty.\n\n >>> list(catalog.findValueTokens(\n ... 'supervisor', {zc.relation.RELATION: 'Frank'}))\n ['Chuck', 'Alice', 'Zane', 'Betty']\n\nPaths returned by ``findRelationChains`` are marked with special interfaces,\nand special metadata, to show the chain.\n\n >>> res = list(catalog.findRelationChains({zc.relation.RELATION: 'Frank'}))\n >>> len(res)\n 5\n >>> import zc.relation.interfaces\n >>> [zc.relation.interfaces.ICircularRelationPath.providedBy(r)\n ... for r in res]\n [False, False, False, False, True]\n\nHere's the last chain:\n\n >>> res[-1] # doctest: +NORMALIZE_WHITESPACE\n cycle(, ,\n , ,\n )\n\nThe chain's 'cycled' attribute has a list of queries that create a cycle.\nIf you run the query, or queries, you see where the cycle would\nrestart--where the path would have started to overlap. Sometimes the query\nresults will include multiple cycles, and some paths that are not cycles.\nIn this case, there's only a single cycled query, which results in a single\ncycled relation.\n\n >>> len(res[4].cycled)\n 1\n\n >>> list(catalog.findRelations(res[4].cycled[0], maxDepth=1))\n []\n\nTo remove this craziness [#reverse_lookup]_, we can unindex Zane, and change\nand reindex Alice.\n\n.. [#reverse_lookup] If you want to, look what happens when you go the\n other way:\n\n >>> res = list(catalog.findRelationChains({'supervisor': 'Zane'}))\n >>> def sortEqualLenByName(one):\n ... return len(one), one\n ...\n >>> res.sort(key=sortEqualLenByName) # normalizes for test stability\n >>> from __future__ import print_function\n >>> print(res) # doctest: +NORMALIZE_WHITESPACE\n [(,),\n (, ),\n (, ),\n (, ,\n ),\n (, ,\n ),\n cycle(, ,\n ),\n (, ,\n ),\n (, ,\n ),\n (, ,\n , )]\n\n >>> [zc.relation.interfaces.ICircularRelationPath.providedBy(r)\n ... for r in res]\n [False, False, False, False, False, True, False, False, False]\n >>> len(res[5].cycled)\n 1\n >>> list(catalog.findRelations(res[5].cycled[0], maxDepth=1))\n []\n\n >>> a.supervisor = None\n >>> catalog.index(a)\n\n >>> list(catalog.findValueTokens(\n ... 'supervisor', {zc.relation.RELATION: 'Frank'}))\n ['Chuck', 'Alice']\n\n >>> catalog.unindex(z)\n\n >>> sorted(catalog.findRelationTokens({'supervisor': 'Betty'}))\n ['Diane', 'Edgar', 'Howie']\n\n``canFind``\n-----------\n\nWe're to the last search method: ``canFind``. We've gotten values and\nrelations, but what if you simply want to know if there is any\nconnection at all? For instance, is Alice a supervisor of Howie? Is\nChuck? To answer these questions, you can use the ``canFind`` method\ncombined with the ``targetQuery`` search argument.\n\nThe ``canFind`` method takes the same arguments as findRelations. However,\nit simply returns a boolean about whether the search has any results. This\nis a convenience that also allows some extra optimizations.\n\nDoes Betty supervise anyone?\n\n >>> catalog.canFind({'supervisor': 'Betty'})\n True\n\nWhat about Howie?\n\n >>> catalog.canFind({'supervisor': 'Howie'})\n False\n\nWhat about...Zane (no longer an employee)?\n\n >>> catalog.canFind({'supervisor': 'Zane'})\n False\n\nIf we want to know if Alice or Chuck supervise Howie, then we want to specify\ncharacteristics of two points on a path. To ask a question about the other\nend of a path, use ``targetQuery``.\n\nIs Alice a supervisor of Howie?\n\n >>> catalog.canFind({'supervisor': 'Alice'},\n ... targetQuery={zc.relation.RELATION: 'Howie'})\n True\n\nIs Chuck a supervisor of Howie?\n\n >>> catalog.canFind({'supervisor': 'Chuck'},\n ... targetQuery={zc.relation.RELATION: 'Howie'})\n False\n\nIs Howie Alice's employee?\n\n >>> catalog.canFind({zc.relation.RELATION: 'Howie'},\n ... targetQuery={'supervisor': 'Alice'})\n True\n\nIs Howie Chuck's employee?\n\n >>> catalog.canFind({zc.relation.RELATION: 'Howie'},\n ... targetQuery={'supervisor': 'Chuck'})\n False\n\n(Note that, if your relations describe a hierarchy, searching up a hierarchy is\nusually more efficient than searching down, so the second pair of questions is\ngenerally preferable to the first in that case.)\n\nWorking with More Complex Relations\n===================================\n\nSo far, our examples have used a simple relation, in which the indexed object\nis one end of the relation, and the indexed value on the object is the other.\nThis example has let us look at all of the basic zc.relation catalog\nfunctionality.\n\nAs mentioned in the introduction, though, the catalog supports, and was\ndesigned for, more complex relations. This section will quickly examine a\nfew examples of other uses.\n\nIn this section, we will see several examples of ideas mentioned above but not\nyet demonstrated.\n\n- We can use interface attributes (values or callables) to define value\n indexes.\n\n- Using interface attributes will cause an attempt to adapt the relation if it\n does not already provide the interface.\n\n- We can use the ``multiple`` argument when defining a value index to indicate\n that the indexed value is a collection.\n\n- We can use the ``name`` argument when defining a value index to specify the\n name to be used in queries, rather than relying on the name of the interface\n attribute or callable.\n\n- The ``family`` argument in instantiating the catalog lets you change the\n default btree family for relations and value indexes from\n ``BTrees.family32.IF`` to ``BTrees.family64.IF``.\n\nExtrinsic Two-Way Relations\n---------------------------\n\nA simple variation of our current story is this: what if the indexed relation\nwere between two other objects--that is, what if the relation were extrinsic to\nboth participants?\n\nLet's imagine we have relations that show biological parentage. We'll want a\n\"Person\" and a \"Parentage\" relation. We'll define an interface for\n``IParentage`` so we can see how using an interface to define a value index\nworks.\n\n >>> class Person(object):\n ... def __init__(self, name):\n ... self.name = name\n ... def __repr__(self):\n ... return '' % (self.name,)\n ...\n >>> import zope.interface\n >>> class IParentage(zope.interface.Interface):\n ... child = zope.interface.Attribute('the child')\n ... parents = zope.interface.Attribute('the parents')\n ...\n >>> @zope.interface.implementer(IParentage)\n ... class Parentage(object):\n ...\n ... def __init__(self, child, parent1, parent2):\n ... self.child = child\n ... self.parents = (parent1, parent2)\n ...\n\nNow we'll define the dumpers and loaders and then the catalog. Notice that\nwe are relying on a pattern: the dump must be called before the load.\n\n >>> _people = {}\n >>> _relations = {}\n >>> def dumpPeople(obj, catalog, cache):\n ... if _people.setdefault(obj.name, obj) is not obj:\n ... raise ValueError('we are assuming names are unique')\n ... return obj.name\n ...\n >>> def loadPeople(token, catalog, cache):\n ... return _people[token]\n ...\n >>> def dumpRelations(obj, catalog, cache):\n ... if _relations.setdefault(id(obj), obj) is not obj:\n ... raise ValueError('huh?')\n ... return id(obj)\n ...\n >>> def loadRelations(token, catalog, cache):\n ... return _relations[token]\n ...\n >>> catalog = zc.relation.catalog.Catalog(dumpRelations, loadRelations, family=BTrees.family64)\n >>> catalog.addValueIndex(IParentage['child'], dumpPeople, loadPeople,\n ... btree=BTrees.family32.OO)\n >>> catalog.addValueIndex(IParentage['parents'], dumpPeople, loadPeople,\n ... btree=BTrees.family32.OO, multiple=True,\n ... name='parent')\n >>> catalog.addDefaultQueryFactory(\n ... zc.relation.queryfactory.TransposingTransitive(\n ... 'child', 'parent'))\n\nNow we have a catalog fully set up. Let's add some relations.\n\n >>> a = Person('Alice')\n >>> b = Person('Betty')\n >>> c = Person('Charles')\n >>> d = Person('Donald')\n >>> e = Person('Eugenia')\n >>> f = Person('Fred')\n >>> g = Person('Gertrude')\n >>> h = Person('Harry')\n >>> i = Person('Iphigenia')\n >>> j = Person('Jacob')\n >>> k = Person('Karyn')\n >>> l = Person('Lee')\n\n >>> r1 = Parentage(child=j, parent1=k, parent2=l)\n >>> r2 = Parentage(child=g, parent1=i, parent2=j)\n >>> r3 = Parentage(child=f, parent1=g, parent2=h)\n >>> r4 = Parentage(child=e, parent1=g, parent2=h)\n >>> r5 = Parentage(child=b, parent1=e, parent2=d)\n >>> r6 = Parentage(child=a, parent1=e, parent2=c)\n\nHere's that in one of our hierarchy diagrams.\n\n::\n\n Karyn Lee\n \\ /\n Jacob Iphigenia\n \\ /\n Gertrude Harry\n \\ /\n /-------\\\n Fred Eugenia\n Donald / \\ Charles\n \\ / \\ /\n Betty Alice\n\nNow we can index the relations, and ask some questions.\n\n >>> for r in (r1, r2, r3, r4, r5, r6):\n ... catalog.index(r)\n >>> query = catalog.tokenizeQuery\n >>> sorted(catalog.findValueTokens(\n ... 'parent', query(child=a), maxDepth=1))\n ['Charles', 'Eugenia']\n >>> sorted(catalog.findValueTokens('parent', query(child=g)))\n ['Iphigenia', 'Jacob', 'Karyn', 'Lee']\n >>> sorted(catalog.findValueTokens(\n ... 'child', query(parent=h), maxDepth=1))\n ['Eugenia', 'Fred']\n >>> sorted(catalog.findValueTokens('child', query(parent=h)))\n ['Alice', 'Betty', 'Eugenia', 'Fred']\n >>> catalog.canFind(query(parent=h), targetQuery=query(child=d))\n False\n >>> catalog.canFind(query(parent=l), targetQuery=query(child=b))\n True\n\nMulti-Way Relations\n-------------------\n\nThe previous example quickly showed how to set the catalog up for a completely\nextrinsic two-way relation. The same pattern can be extended for N-way\nrelations. For example, consider a four way relation in the form of\nSUBJECTS PREDICATE OBJECTS [in CONTEXT]. For instance, we might\nwant to say \"(joe,) SELLS (doughnuts, coffee) in corner_store\", where \"(joe,)\"\nis the collection of subjects, \"SELLS\" is the predicate, \"(doughnuts, coffee)\"\nis the collection of objects, and \"corner_store\" is the optional context.\n\nFor this last example, we'll integrate two components we haven't seen examples\nof here before: the ZODB and adaptation.\n\nOur example ZODB approach uses OIDs as the tokens. this might be OK in some\ncases, if you will never support multiple databases and you don't need an\nabstraction layer so that a different object can have the same identifier.\n\n >>> import persistent\n >>> import struct\n >>> class Demo(persistent.Persistent):\n ... def __init__(self, name):\n ... self.name = name\n ... def __repr__(self):\n ... return '' % (self.name,)\n ...\n >>> class IRelation(zope.interface.Interface):\n ... subjects = zope.interface.Attribute('subjects')\n ... predicate = zope.interface.Attribute('predicate')\n ... objects = zope.interface.Attribute('objects')\n ...\n >>> class IContextual(zope.interface.Interface):\n ... def getContext():\n ... 'return context'\n ... def setContext(value):\n ... 'set context'\n ...\n >>> @zope.interface.implementer(IContextual)\n ... class Contextual(object):\n ...\n ... _context = None\n ... def getContext(self):\n ... return self._context\n ... def setContext(self, value):\n ... self._context = value\n ...\n >>> @zope.interface.implementer(IRelation)\n ... class Relation(persistent.Persistent):\n ...\n ... def __init__(self, subjects, predicate, objects):\n ... self.subjects = subjects\n ... self.predicate = predicate\n ... self.objects = objects\n ... self._contextual = Contextual()\n ...\n ... def __conform__(self, iface):\n ... if iface is IContextual:\n ... return self._contextual\n ...\n\n(When using zope.component, the ``__conform__`` would normally be unnecessary;\nhowever, this package does not depend on zope.component.)\n\n >>> def dumpPersistent(obj, catalog, cache):\n ... if obj._p_jar is None:\n ... catalog._p_jar.add(obj) # assumes something else places it\n ... return struct.unpack('>> def loadPersistent(token, catalog, cache):\n ... return catalog._p_jar.get(struct.pack('>> from ZODB.tests.util import DB\n >>> db = DB()\n >>> conn = db.open()\n >>> root = conn.root()\n >>> catalog = root['catalog'] = zc.relation.catalog.Catalog(\n ... dumpPersistent, loadPersistent, family=BTrees.family64)\n >>> catalog.addValueIndex(IRelation['subjects'],\n ... dumpPersistent, loadPersistent, multiple=True, name='subject')\n >>> catalog.addValueIndex(IRelation['objects'],\n ... dumpPersistent, loadPersistent, multiple=True, name='object')\n >>> catalog.addValueIndex(IRelation['predicate'], btree=BTrees.family32.OO)\n >>> catalog.addValueIndex(IContextual['getContext'],\n ... dumpPersistent, loadPersistent, name='context')\n >>> import transaction\n >>> transaction.commit()\n\nThe ``dumpPersistent`` and ``loadPersistent`` is a bit of a toy, as warned\nabove. Also, while our predicate will be stored as a string, some programmers\nmay prefer to have a dump in such a case verify that the string has been\nexplicitly registered in some way, to prevent typos. Obviously, we are not\nbothering with this for our example.\n\nWe make some objects, and then we make some relations with those objects and\nindex them.\n\n >>> joe = root['joe'] = Demo('joe')\n >>> sara = root['sara'] = Demo('sara')\n >>> jack = root['jack'] = Demo('jack')\n >>> ann = root['ann'] = Demo('ann')\n >>> doughnuts = root['doughnuts'] = Demo('doughnuts')\n >>> coffee = root['coffee'] = Demo('coffee')\n >>> muffins = root['muffins'] = Demo('muffins')\n >>> cookies = root['cookies'] = Demo('cookies')\n >>> newspaper = root['newspaper'] = Demo('newspaper')\n >>> corner_store = root['corner_store'] = Demo('corner_store')\n >>> bistro = root['bistro'] = Demo('bistro')\n >>> bakery = root['bakery'] = Demo('bakery')\n\n >>> SELLS = 'SELLS'\n >>> BUYS = 'BUYS'\n >>> OBSERVES = 'OBSERVES'\n\n >>> rel1 = root['rel1'] = Relation((joe,), SELLS, (doughnuts, coffee))\n >>> IContextual(rel1).setContext(corner_store)\n >>> rel2 = root['rel2'] = Relation((sara, jack), SELLS,\n ... (muffins, doughnuts, cookies))\n >>> IContextual(rel2).setContext(bakery)\n >>> rel3 = root['rel3'] = Relation((ann,), BUYS, (doughnuts,))\n >>> rel4 = root['rel4'] = Relation((sara,), BUYS, (bistro,))\n\n >>> for r in (rel1, rel2, rel3, rel4):\n ... catalog.index(r)\n ...\n\nNow we can ask a simple question. Where do they sell doughnuts?\n\n >>> query = catalog.tokenizeQuery\n >>> sorted(catalog.findValues(\n ... 'context',\n ... (query(predicate=SELLS, object=doughnuts))),\n ... key=lambda ob: ob.name)\n [, ]\n\nHopefully these examples give you further ideas on how you can use this tool.\n\nAdditional Functionality\n========================\n\nThis section introduces peripheral functionality. We will learn the following.\n\n- Listeners can be registered in the catalog. They are alerted when a relation\n is added, modified, or removed; and when the catalog is cleared and copied\n (see below).\n\n- The ``clear`` method clears the relations in the catalog.\n\n- The ``copy`` method makes a copy of the current catalog by copying internal\n data structures, rather than reindexing the relations, which can be a\n significant optimization opportunity. This copies value indexes and search\n indexes; and gives listeners an opportunity to specify what, if anything,\n should be included in the new copy.\n\n- The ``ignoreSearchIndex`` argument to the five pertinent search methods\n causes the search to ignore search indexes, even if there is an appropriate\n one.\n\n- ``findRelationTokens()`` (without arguments) returns the BTree set of all\n relation tokens in the catalog.\n\n- ``findValueTokens(INDEX_NAME)`` (where \"INDEX_NAME\" should be replaced with\n an index name) returns the BTree set of all value tokens in the catalog for\n the given index name.\n\nListeners\n---------\n\nA variety of potential clients may want to be alerted when the catalog changes.\nzc.relation does not depend on zope.event, so listeners may be registered for\nvarious changes. Let's make a quick demo listener. The ``additions`` and\n``removals`` arguments are dictionaries of {value name: iterable of added or\nremoved value tokens}.\n\n >>> def pchange(d):\n ... pprint.pprint(dict(\n ... (k, v is not None and sorted(set(v)) or v) for k, v in d.items()))\n >>> @zope.interface.implementer(zc.relation.interfaces.IListener)\n ... class DemoListener(persistent.Persistent):\n ...\n ... def relationAdded(self, token, catalog, additions):\n ... print('a relation (token %r) was added to %r '\n ... 'with these values:' % (token, catalog))\n ... pchange(additions)\n ... def relationModified(self, token, catalog, additions, removals):\n ... print('a relation (token %r) in %r was modified '\n ... 'with these additions:' % (token, catalog))\n ... pchange(additions)\n ... print('and these removals:')\n ... pchange(removals)\n ... def relationRemoved(self, token, catalog, removals):\n ... print('a relation (token %r) was removed from %r '\n ... 'with these values:' % (token, catalog))\n ... pchange(removals)\n ... def sourceCleared(self, catalog):\n ... print('catalog %r had all relations unindexed' % (catalog,))\n ... def sourceAdded(self, catalog):\n ... print('now listening to catalog %r' % (catalog,))\n ... def sourceRemoved(self, catalog):\n ... print('no longer listening to catalog %r' % (catalog,))\n ... def sourceCopied(self, original, copy):\n ... print('catalog %r made a copy %r' % (catalog, copy))\n ... copy.addListener(self)\n ...\n\nListeners can be installed multiple times.\n\nListeners can be added as persistent weak references, so that, if they are\ndeleted elsewhere, a ZODB pack will not consider the reference in the catalog\nto be something preventing garbage collection.\n\nWe'll install one of these demo listeners into our new catalog as a\nnormal reference, the default behavior. Then we'll show some example messages\nsent to the demo listener.\n\n >>> listener = DemoListener()\n >>> catalog.addListener(listener) # doctest: +ELLIPSIS\n now listening to catalog \n >>> rel5 = root['rel5'] = Relation((ann,), OBSERVES, (newspaper,))\n >>> catalog.index(rel5) # doctest: +ELLIPSIS\n a relation (token ...) was added to <...Catalog...> with these values:\n {'context': None,\n 'object': [...],\n 'predicate': ['OBSERVES'],\n 'subject': [...]}\n >>> rel5.subjects = (jack,)\n >>> IContextual(rel5).setContext(bistro)\n >>> catalog.index(rel5) # doctest: +ELLIPSIS\n a relation (token ...) in ...Catalog... was modified with these additions:\n {'context': [...], 'subject': [...]}\n and these removals:\n {'subject': [...]}\n >>> catalog.unindex(rel5) # doctest: +ELLIPSIS\n a relation (token ...) was removed from <...Catalog...> with these values:\n {'context': [...],\n 'object': [...],\n 'predicate': ['OBSERVES'],\n 'subject': [...]}\n\n >>> catalog.removeListener(listener) # doctest: +ELLIPSIS\n no longer listening to catalog <...Catalog...>\n >>> catalog.index(rel5) # doctest: +ELLIPSIS\n\nThe only two methods not shown by those examples are ``sourceCleared`` and\n``sourceCopied``. We'll get to those very soon below.\n\nThe ``clear`` Method\n--------------------\n\nThe ``clear`` method simply indexes all relations from a catalog. Installed\nlisteners have ``sourceCleared`` called.\n\n >>> len(catalog)\n 5\n\n >>> catalog.addListener(listener) # doctest: +ELLIPSIS\n now listening to catalog \n\n >>> catalog.clear() # doctest: +ELLIPSIS\n catalog <...Catalog...> had all relations unindexed\n\n >>> len(catalog)\n 0\n >>> sorted(catalog.findValues(\n ... 'context',\n ... (query(predicate=SELLS, object=doughnuts))),\n ... key=lambda ob: ob.name)\n []\n\nThe ``copy`` Method\n-------------------\n\nSometimes you may want to copy a relation catalog. One way of doing this is\nto create a new catalog, set it up like the current one, and then reindex\nall the same relations. This is unnecessarily slow for programmer and\ncomputer. The ``copy`` method makes a new catalog with the same corpus of\nindexed relations by copying internal data structures.\n\nSearch indexes are requested to make new copies of themselves for the new\ncatalog; and listeners are given an opportunity to react as desired to the new\ncopy, including installing themselves, and/or another object of their choosing\nas a listener.\n\nLet's make a copy of a populated index with a search index and a listener.\nNotice in our listener that ``sourceCopied`` adds itself as a listener to the\nnew copy. This is done at the very end of the ``copy`` process.\n\n >>> for r in (rel1, rel2, rel3, rel4, rel5):\n ... catalog.index(r)\n ... # doctest: +ELLIPSIS\n a relation ... was added...\n a relation ... was added...\n a relation ... was added...\n a relation ... was added...\n a relation ... was added...\n >>> BEGAT = 'BEGAT'\n >>> rel6 = root['rel6'] = Relation((jack, ann), BEGAT, (sara,))\n >>> henry = root['henry'] = Demo('henry')\n >>> rel7 = root['rel7'] = Relation((sara, joe), BEGAT, (henry,))\n >>> catalog.index(rel6) # doctest: +ELLIPSIS\n a relation (token ...) was added to <...Catalog...> with these values:\n {'context': None,\n 'object': [...],\n 'predicate': ['BEGAT'],\n 'subject': [..., ...]}\n >>> catalog.index(rel7) # doctest: +ELLIPSIS\n a relation (token ...) was added to <...Catalog...> with these values:\n {'context': None,\n 'object': [...],\n 'predicate': ['BEGAT'],\n 'subject': [..., ...]}\n >>> catalog.addDefaultQueryFactory(\n ... zc.relation.queryfactory.TransposingTransitive(\n ... 'subject', 'object', {'predicate': BEGAT}))\n ...\n >>> list(catalog.findValues(\n ... 'object', query(subject=jack, predicate=BEGAT)))\n [, ]\n >>> catalog.addSearchIndex(\n ... zc.relation.searchindex.TransposingTransitiveMembership(\n ... 'subject', 'object', static={'predicate': BEGAT}))\n >>> sorted(\n ... catalog.findValues(\n ... 'object', query(subject=jack, predicate=BEGAT)),\n ... key=lambda o: o.name)\n [, ]\n\n >>> newcat = root['newcat'] = catalog.copy() # doctest: +ELLIPSIS\n catalog <...Catalog...> made a copy <...Catalog...>\n now listening to catalog <...Catalog...>\n >>> transaction.commit()\n\nNow the copy has its own copies of internal data structures and of the\nsearchindex. For example, let's modify the relations and add a new one to the\ncopy.\n\n >>> mary = root['mary'] = Demo('mary')\n >>> buffy = root['buffy'] = Demo('buffy')\n >>> zack = root['zack'] = Demo('zack')\n >>> rel7.objects += (mary,)\n >>> rel8 = root['rel8'] = Relation((henry, buffy), BEGAT, (zack,))\n >>> newcat.index(rel7) # doctest: +ELLIPSIS\n a relation (token ...) in ...Catalog... was modified with these additions:\n {'object': [...]}\n and these removals:\n {}\n >>> newcat.index(rel8) # doctest: +ELLIPSIS\n a relation (token ...) was added to ...Catalog... with these values:\n {'context': None,\n 'object': [...],\n 'predicate': ['BEGAT'],\n 'subject': [..., ...]}\n >>> len(newcat)\n 8\n >>> sorted(\n ... newcat.findValues(\n ... 'object', query(subject=jack, predicate=BEGAT)),\n ... key=lambda o: o.name) # doctest: +NORMALIZE_WHITESPACE\n [, , ,\n ]\n >>> sorted(\n ... newcat.findValues(\n ... 'object', query(subject=sara)),\n ... key=lambda o: o.name) # doctest: +NORMALIZE_WHITESPACE\n [, ,\n , ,\n , ]\n\nThe original catalog is not modified.\n\n >>> len(catalog)\n 7\n >>> sorted(\n ... catalog.findValues(\n ... 'object', query(subject=jack, predicate=BEGAT)),\n ... key=lambda o: o.name)\n [, ]\n >>> sorted(\n ... catalog.findValues(\n ... 'object', query(subject=sara)),\n ... key=lambda o: o.name) # doctest: +NORMALIZE_WHITESPACE\n [, ,\n , ,\n ]\n\nThe ``ignoreSearchIndex`` argument\n----------------------------------\n\nThe five methods that can use search indexes, ``findValues``,\n``findValueTokens``, ``findRelations``, ``findRelationTokens``, and\n``canFind``, can be explicitly requested to ignore any pertinent search index\nusing the ``ignoreSearchIndex`` argument.\n\nWe can see this easily with the token-related methods: the search index result\nwill be a BTree set, while without the search index the result will be a\ngenerator.\n\n >>> res1 = newcat.findValueTokens(\n ... 'object', query(subject=jack, predicate=BEGAT))\n >>> res1 # doctest: +ELLIPSIS\n LFSet([..., ..., ..., ...])\n >>> res2 = newcat.findValueTokens(\n ... 'object', query(subject=jack, predicate=BEGAT),\n ... ignoreSearchIndex=True)\n >>> res2 # doctest: +ELLIPSIS\n \n >>> sorted(res2) == list(res1)\n True\n\n >>> res1 = newcat.findRelationTokens(\n ... query(subject=jack, predicate=BEGAT))\n >>> res1 # doctest: +ELLIPSIS\n LFSet([..., ..., ...])\n >>> res2 = newcat.findRelationTokens(\n ... query(subject=jack, predicate=BEGAT), ignoreSearchIndex=True)\n >>> res2 # doctest: +ELLIPSIS\n \n >>> sorted(res2) == list(res1)\n True\n\nWe can see that the other methods take the argument, but the results look the\nsame as usual.\n\n >>> res = newcat.findValues(\n ... 'object', query(subject=jack, predicate=BEGAT),\n ... ignoreSearchIndex=True)\n >>> res # doctest: +ELLIPSIS\n \n >>> list(res) == list(newcat.resolveValueTokens(newcat.findValueTokens(\n ... 'object', query(subject=jack, predicate=BEGAT),\n ... ignoreSearchIndex=True), 'object'))\n True\n\n >>> res = newcat.findRelations(\n ... query(subject=jack, predicate=BEGAT),\n ... ignoreSearchIndex=True)\n >>> res # doctest: +ELLIPSIS\n \n >>> list(res) == list(newcat.resolveRelationTokens(\n ... newcat.findRelationTokens(\n ... query(subject=jack, predicate=BEGAT),\n ... ignoreSearchIndex=True)))\n True\n\n >>> newcat.canFind(\n ... query(subject=jack, predicate=BEGAT), ignoreSearchIndex=True)\n True\n\n``findRelationTokens()``\n------------------------\n\nIf you call ``findRelationTokens`` without any arguments, you will get the\nBTree set of all relation tokens in the catalog. This can be handy for tests\nand for advanced uses of the catalog.\n\n >>> newcat.findRelationTokens() # doctest: +ELLIPSIS\n \n >>> len(newcat.findRelationTokens())\n 8\n >>> set(newcat.resolveRelationTokens(newcat.findRelationTokens())) == set(\n ... (rel1, rel2, rel3, rel4, rel5, rel6, rel7, rel8))\n True\n\n``findValueTokens(INDEX_NAME)``\n-------------------------------\n\nIf you call ``findValueTokens`` with only an index name, you will get the BTree\nstructure of all tokens for that value in the index. This can be handy for\ntests and for advanced uses of the catalog.\n\n >>> newcat.findValueTokens('predicate') # doctest: +ELLIPSIS\n \n >>> list(newcat.findValueTokens('predicate'))\n ['BEGAT', 'BUYS', 'OBSERVES', 'SELLS']\n\nConclusion\n==========\n\nReview\n------\n\nThat brings us to the end of our introductory examples. Let's review, and\nthen look at where you can go from here.\n\n* Relations are objects with indexed values.\n\n* The relation catalog indexes relations. The relations can be one-way,\n two-way, three-way, or N-way, as long as you tell the catalog to index the\n different values.\n\n* Creating a catalog:\n\n - Relations and their values are stored in the catalog as tokens: unique\n identifiers that you can resolve back to the original value. Integers are\n the most efficient tokens, but others can work fine too.\n\n - Token type determines the BTree module needed.\n\n - If the tokens are 32-bit ints, choose ``BTrees.family32.II``,\n ``BTrees.family32.IF`` or ``BTrees.family32.IO``.\n\n - If the tokens are 64 bit ints, choose ``BTrees.family64.II``,\n ``BTrees.family64.IF`` or ``BTrees.family64.IO``.\n\n - If they are anything else, choose ``BTrees.family32.OI``,\n ``BTrees.family64.OI``, or ``BTrees.family32.OO`` (or\n BTrees.family64.OO--they are the same).\n\n Within these rules, the choice is somewhat arbitrary unless you plan to\n merge these results with that of another source that is using a\n particular BTree module. BTree set operations only work within the same\n module, so you must match module to module.\n\n - The ``family`` argument in instantiating the catalog lets you change the\n default btree family for relations and value indexes from\n ``BTrees.family32.IF`` to ``BTrees.family64.IF``.\n\n - You must define your own functions for tokenizing and resolving tokens.\n These functions are registered with the catalog for the relations and for\n each of their value indexes.\n\n - You add value indexes to relation catalogs to be able to search. Values\n can be identified to the catalog with callables or interface elements.\n\n - Using interface attributes will cause an attempt to adapt the\n relation if it does not already provide the interface.\n\n - We can use the ``multiple`` argument when defining a value index to\n indicate that the indexed value is a collection. This defaults to\n False.\n\n - We can use the ``name`` argument when defining a value index to\n specify the name to be used in queries, rather than relying on the\n name of the interface attribute or callable.\n\n - You can set up search indexes to speed up specific searches, usually\n transitive.\n\n - Listeners can be registered in the catalog. They are alerted when a\n relation is added, modified, or removed; and when the catalog is cleared\n and copied.\n\n* Catalog Management:\n\n - Relations are indexed with ``index(relation)``, and removed from the\n catalog with ``unindex(relation)``. ``index_doc(relation_token,\n relation)`` and ``unindex_doc(relation_token)`` also work.\n\n - The ``clear`` method clears the relations in the catalog.\n\n - The ``copy`` method makes a copy of the current catalog by copying\n internal data structures, rather than reindexing the relations, which can\n be a significant optimization opportunity. This copies value indexes and\n search indexes; and gives listeners an opportunity to specify what, if\n anything, should be included in the new copy.\n\n* Searching a catalog:\n\n - Queries to the relation catalog are formed with dicts.\n\n - Query keys are the names of the indexes you want to search, or, for the\n special case of precise relations, the ``zc.relation.RELATION`` constant.\n\n - Query values are the tokens of the results you want to match; or\n ``None``, indicating relations that have ``None`` as a value (or an empty\n collection, if it is a multiple). Search values can use\n ``zc.relation.catalog.any(args)`` or ``zc.relation.catalog.Any(args)`` to\n specify multiple (non-``None``) results to match for a given key.\n\n - The index has a variety of methods to help you work with tokens.\n ``tokenizeQuery`` is typically the most used, though others are\n available.\n\n - To find relations that match a query, use ``findRelations`` or\n ``findRelationTokens``. Calling ``findRelationTokens`` without any\n arguments returns the BTree set of all relation tokens in the catalog.\n\n - To find values that match a query, use ``findValues`` or\n ``findValueTokens``. Calling ``findValueTokens`` with only the name\n of a value index returns the BTree set of all tokens in the catalog for\n that value index.\n\n - You search transitively by using a query factory. The\n ``zc.relation.queryfactory.TransposingTransitive`` is a good common case\n factory that lets you walk up and down a hierarchy. A query factory can\n be passed in as an argument to search methods as a ``queryFactory``, or\n installed as a default behavior using ``addDefaultQueryFactory``.\n\n - To find how a query is related, use ``findRelationChains`` or\n ``findRelationTokenChains``.\n\n - To find out if a query is related, use ``canFind``.\n\n - Circular transitive relations are handled to prevent infinite loops. They\n are identified in ``findRelationChains`` and ``findRelationTokenChains``\n with a ``zc.relation.interfaces.ICircularRelationPath`` marker interface.\n\n - search methods share the following arguments:\n\n * ``maxDepth``, limiting the transitive depth for searches;\n\n * ``filter``, allowing code to filter transitive paths;\n\n * ``targetQuery``, allowing a query to filter transitive paths on the\n basis of the endpoint;\n\n * ``targetFilter``, allowing code to filter transitive paths on the basis\n of the endpoint; and\n\n * ``queryFactory``, mentioned above.\n\n In addition, the ``ignoreSearchIndex`` argument to ``findRelations``,\n ``findRelationTokens``, ``findValues``, ``findValueTokens``, and\n ``canFind`` causes the search to ignore search indexes, even if there is\n an appropriate one.\n\nNext Steps\n----------\n\nIf you want to read more, next steps depend on how you like to learn. Here\nare some of the other documents in the zc.relation package.\n\n:optimization.rst:\n Best practices for optimizing your use of the relation catalog.\n\n:searchindex.rst:\n Queries factories and search indexes: from basics to nitty gritty details.\n\n:tokens.rst:\n This document explores the details of tokens. All God's chillun\n love tokens, at least if God's chillun are writing non-toy apps\n using zc.relation. It includes discussion of the token helpers that\n the catalog provides, how to use zope.app.intid-like registries with\n zc.relation, how to use tokens to \"join\" query results reasonably\n efficiently, and how to index joins. It also is unnecessarily\n mind-blowing because of the examples used.\n\n:interfaces.py:\n The contract, for nuts and bolts.\n\nFinally, the truly die-hard might also be interested in the timeit\ndirectory, which holds scripts used to test assumptions and learn.\n\n.. ......... ..\n.. FOOTNOTES ..\n.. ......... ..\n\n.. [#I_care] OK, you care about how that query factory worked, so\n we will look into it a bit. Let's talk through two steps of the\n transitive search in the second question. The catalog initially\n performs the initial intransitive search requested: find relations\n for which Betty is the supervisor. That's Diane and Edgar.\n\n Now, for each of the results, the catalog asks the query factory for\n next steps. Let's take Diane. The catalog says to the factory,\n \"Given this query for relations where Betty is supervisor, I got\n this result of Diane. Do you have any other queries I should try to\n look further?\". The factory also gets the catalog instance so it\n can use it to answer the question if it needs to.\n\n OK, the next part is where your brain hurts. Hang on.\n\n In our case, the factory sees that the query was for supervisor. Its\n other key, the one it transposes with, is ``zc.relation.RELATION``. *The\n factory gets the transposing key's result for the current token.* So, for\n us, a key of ``zc.relation.RELATION`` is actually a no-op: the result *is*\n the current token, Diane. Then, the factory has its answer: replace the old\n value of supervisor in the query, Betty, with the result, Diane. The next\n transitive query should be {'supervisor', 'Diane'}. Ta-da.\n\n\n======================================================\nTokens and Joins: zc.relation Catalog Extended Example\n======================================================\n\nIntroduction and Set Up\n=======================\n\nThis document assumes you have read the introductory README.rst and want\nto learn a bit more by example. In it, we will explore a more\ncomplicated set of relations that demonstrates most of the aspects of\nworking with tokens. In particular, we will look at joins, which will\nalso give us a chance to look more in depth at query factories and\nsearch indexes, and introduce the idea of listeners. It will not explain\nthe basics that the README already addressed.\n\nImagine we are indexing security assertions in a system. In this\nsystem, users may have roles within an organization. Each organization\nmay have multiple child organizations and may have a single parent\norganization. A user with a role in a parent organization will have the\nsame role in all transitively connected child relations.\n\nWe have two kinds of relations, then. One kind of relation will model\nthe hierarchy of organizations. We'll do it with an intrinsic relation\nof organizations to their children: that reflects the fact that parent\norganizations choose and are comprised of their children; children do\nnot choose their parents.\n\nThe other relation will model the (multiple) roles a (single) user has\nin a (single) organization. This relation will be entirely extrinsic.\n\nWe could create two catalogs, one for each type. Or we could put them\nboth in the same catalog. Initially, we'll go with the single-catalog\napproach for our examples. This single catalog, then, will be indexing\na heterogeneous collection of relations.\n\nLet's define the two relations with interfaces. We'll include one\naccessor, getOrganization, largely to show how to handle methods.\n\n >>> import zope.interface\n >>> class IOrganization(zope.interface.Interface):\n ... title = zope.interface.Attribute('the title')\n ... parts = zope.interface.Attribute(\n ... 'the organizations that make up this one')\n ...\n >>> class IRoles(zope.interface.Interface):\n ... def getOrganization():\n ... 'return the organization in which this relation operates'\n ... principal_id = zope.interface.Attribute(\n ... 'the pricipal id whose roles this relation lists')\n ... role_ids = zope.interface.Attribute(\n ... 'the role ids that the principal explicitly has in the '\n ... 'organization. The principal may have other roles via '\n ... 'roles in parent organizations.')\n ...\n\nNow we can create some classes. In the README example, the setup was a bit\nof a toy. This time we will be just a bit more practical. We'll also expect\nto be operating within the ZODB, with a root and transactions. [#ZODB]_\n\n.. [#ZODB] Here we will set up a ZODB instance for us to use.\n\n >>> from ZODB.tests.util import DB\n >>> db = DB()\n >>> conn = db.open()\n >>> root = conn.root()\n\nHere's how we will dump and load our relations: use a \"registry\"\nobject, similar to an intid utility. [#faux_intid]_\n\n.. [#faux_intid] Here's a simple persistent keyreference. Notice that it is\n not persistent itself: this is important for conflict resolution to be\n able to work (which we don't show here, but we're trying to lean more\n towards real usage for this example).\n\n >>> from functools import total_ordering\n >>> @total_ordering\n ... class Reference(object): # see zope.app.keyreference\n ... def __init__(self, obj):\n ... self.object = obj\n ... def _get_sorting_key(self):\n ... # this doesn't work during conflict resolution. See\n ... # zope.app.keyreference.persistent, 3.5 release, for current\n ... # best practice.\n ... if self.object._p_jar is None:\n ... raise ValueError(\n ... 'can only compare when both objects have connections')\n ... return self.object._p_oid or ''\n ... def __lt__(self, other):\n ... # this doesn't work during conflict resolution. See\n ... # zope.app.keyreference.persistent, 3.5 release, for current\n ... # best practice.\n ... if not isinstance(other, Reference):\n ... raise ValueError('can only compare with Reference objects')\n ... return self._get_sorting_key() < other._get_sorting_key()\n ... def __eq__(self, other):\n ... # this doesn't work during conflict resolution. See\n ... # zope.app.keyreference.persistent, 3.5 release, for current\n ... # best practice.\n ... if not isinstance(other, Reference):\n ... raise ValueError('can only compare with Reference objects')\n ... return self._get_sorting_key() == other._get_sorting_key()\n\n Here's a simple integer identifier tool.\n\n >>> import persistent\n >>> import BTrees\n >>> import six\n >>> class Registry(persistent.Persistent): # see zope.app.intid\n ... def __init__(self, family=BTrees.family32):\n ... self.family = family\n ... self.ids = self.family.IO.BTree()\n ... self.refs = self.family.OI.BTree()\n ... def getId(self, obj):\n ... if not isinstance(obj, persistent.Persistent):\n ... raise ValueError('not a persistent object', obj)\n ... if obj._p_jar is None:\n ... self._p_jar.add(obj)\n ... ref = Reference(obj)\n ... id = self.refs.get(ref)\n ... if id is None:\n ... # naive for conflict resolution; see zope.app.intid\n ... if self.ids:\n ... id = self.ids.maxKey() + 1\n ... else:\n ... id = self.family.minint\n ... self.ids[id] = ref\n ... self.refs[ref] = id\n ... return id\n ... def __contains__(self, obj):\n ... if (not isinstance(obj, persistent.Persistent) or\n ... obj._p_oid is None):\n ... return False\n ... return Reference(obj) in self.refs\n ... def getObject(self, id, default=None):\n ... res = self.ids.get(id, None)\n ... if res is None:\n ... return default\n ... else:\n ... return res.object\n ... def remove(self, r):\n ... if isinstance(r, six.integer_types):\n ... self.refs.pop(self.ids.pop(r))\n ... elif (not isinstance(r, persistent.Persistent) or\n ... r._p_oid is None):\n ... raise LookupError(r)\n ... else:\n ... self.ids.pop(self.refs.pop(Reference(r)))\n ...\n >>> registry = root['registry'] = Registry()\n\n >>> import transaction\n >>> transaction.commit()\n\nIn this implementation of the \"dump\" method, we use the cache just to\nshow you how you might use it. It probably is overkill for this job,\nand maybe even a speed loss, but you can see the idea.\n\n >>> def dump(obj, catalog, cache):\n ... reg = cache.get('registry')\n ... if reg is None:\n ... reg = cache['registry'] = catalog._p_jar.root()['registry']\n ... return reg.getId(obj)\n ...\n >>> def load(token, catalog, cache):\n ... reg = cache.get('registry')\n ... if reg is None:\n ... reg = cache['registry'] = catalog._p_jar.root()['registry']\n ... return reg.getObject(token)\n ...\n\nNow we can create a relation catalog to hold these items.\n\n >>> import zc.relation.catalog\n >>> catalog = root['catalog'] = zc.relation.catalog.Catalog(dump, load)\n >>> transaction.commit()\n\nNow we set up our indexes. We'll start with just the organizations, and\nset up the catalog with them. This part will be similar to the example\nin README.rst, but will introduce more discussions of optimizations and\ntokens. Then we'll add in the part about roles, and explore queries and\ntoken-based \"joins\".\n\nOrganizations\n=============\n\nThe organization will hold a set of organizations. This is actually not\ninherently easy in the ZODB because this means that we need to compare\nor hash persistent objects, which does not work reliably over time and\nacross machines out-of-the-box. To side-step the issue for this example,\nand still do something a bit interesting and real-world, we'll use the\nregistry tokens introduced above. This will also give us a chance to\ntalk a bit more about optimizations and tokens. (If you would like\nto sanely and transparently hold a set of persistent objects, try the\nzc.set package XXX not yet.)\n\n >>> import BTrees\n >>> import persistent\n >>> @zope.interface.implementer(IOrganization)\n ... @total_ordering\n ... class Organization(persistent.Persistent):\n ...\n ... def __init__(self, title):\n ... self.title = title\n ... self.parts = BTrees.family32.IF.TreeSet()\n ... # the next parts just make the tests prettier\n ... def __repr__(self):\n ... return ''\n ... def __lt__(self, other):\n ... # pukes if other doesn't have name\n ... return self.title < other.title\n ... def __eq__(self, other):\n ... return self is other\n ... def __hash__(self):\n ... return 1 # dummy\n ...\n\nOK, now we know how organizations will work. Now we can add the `parts`\nindex to the catalog. This will do a few new things from how we added\nindexes in the README.\n\n\n >>> catalog.addValueIndex(IOrganization['parts'], multiple=True,\n ... name=\"part\")\n\nSo, what's different from the README examples?\n\nFirst, we are using an interface element to define the value to be indexed.\nIt provides an interface to which objects will be adapted, a default name\nfor the index, and information as to whether the attribute should be used\ndirectly or called.\n\nSecond, we are not specifying a dump or load. They are None. This\nmeans that the indexed value can already be treated as a token. This\ncan allow a very significant optimization for reindexing if the indexed\nvalue is a large collection using the same BTree family as the\nindex--which leads us to the next difference.\n\nThird, we are specifying that `multiple=True`. This means that the value\non a given relation that provides or can be adapted to IOrganization will\nhave a collection of `parts`. These will always be regarded as a set,\nwhether the actual colection is a BTrees set or the keys of a BTree.\n\nLast, we are specifying a name to be used for queries. I find that queries\nread more easily when the query keys are singular, so I often rename plurals.\n\nAs in the README, We can add another simple transposing transitive query\nfactory, switching between 'part' and `None`.\n\n >>> import zc.relation.queryfactory\n >>> factory1 = zc.relation.queryfactory.TransposingTransitive(\n ... 'part', None)\n >>> catalog.addDefaultQueryFactory(factory1)\n\nLet's add a couple of search indexes in too, of the hierarchy looking up...\n\n >>> import zc.relation.searchindex\n >>> catalog.addSearchIndex(\n ... zc.relation.searchindex.TransposingTransitiveMembership(\n ... 'part', None))\n\n...and down.\n\n >>> catalog.addSearchIndex(\n ... zc.relation.searchindex.TransposingTransitiveMembership(\n ... None, 'part'))\n\nPLEASE NOTE: the search index looking up is not a good idea practically. The\nindex is designed for looking down [#verifyObjectTransitive]_.\n\n.. [#verifyObjectTransitive] The TransposingTransitiveMembership indexes\n provide ISearchIndex.\n\n >>> from zope.interface.verify import verifyObject\n >>> import zc.relation.interfaces\n >>> index = list(catalog.iterSearchIndexes())[0]\n >>> verifyObject(zc.relation.interfaces.ISearchIndex, index)\n True\n\nLet's create and add a few organizations.\n\nWe'll make a structure like this [#silliness]_::\n\n Ynod Corp Mangement Zookd Corp Management\n / | \\ / | \\\n Ynod Devs Ynod SAs Ynod Admins Zookd Admins Zookd SAs Zookd Devs\n / \\ \\ / / \\\n Y3L4 Proj Bet Proj Ynod Zookd Task Force Zookd hOgnmd Zookd Nbd\n\nHere's the Python.\n\n\n >>> orgs = root['organizations'] = BTrees.family32.OO.BTree()\n >>> for nm, parts in (\n ... ('Y3L4 Proj', ()),\n ... ('Bet Proj', ()),\n ... ('Ynod Zookd Task Force', ()),\n ... ('Zookd hOgnmd', ()),\n ... ('Zookd Nbd', ()),\n ... ('Ynod Devs', ('Y3L4 Proj', 'Bet Proj')),\n ... ('Ynod SAs', ()),\n ... ('Ynod Admins', ('Ynod Zookd Task Force',)),\n ... ('Zookd Admins', ('Ynod Zookd Task Force',)),\n ... ('Zookd SAs', ()),\n ... ('Zookd Devs', ('Zookd hOgnmd', 'Zookd Nbd')),\n ... ('Ynod Corp Management', ('Ynod Devs', 'Ynod SAs', 'Ynod Admins')),\n ... ('Zookd Corp Management', ('Zookd Devs', 'Zookd SAs',\n ... 'Zookd Admins'))):\n ... org = Organization(nm)\n ... for part in parts:\n ... ignore = org.parts.insert(registry.getId(orgs[part]))\n ... orgs[nm] = org\n ... catalog.index(org)\n ...\n\nNow the catalog knows about the relations.\n\n >>> len(catalog)\n 13\n >>> root['dummy'] = Organization('Foo')\n >>> root['dummy'] in catalog\n False\n >>> orgs['Y3L4 Proj'] in catalog\n True\n\nAlso, now we can search. To do this, we can use some of the token methods that\nthe catalog provides. The most commonly used is `tokenizeQuery`. It takes a\nquery with values that are not tokenized and converts them to values that are\ntokenized.\n\n >>> Ynod_SAs_id = registry.getId(orgs['Ynod SAs'])\n >>> catalog.tokenizeQuery({None: orgs['Ynod SAs']}) == {\n ... None: Ynod_SAs_id}\n True\n >>> Zookd_SAs_id = registry.getId(orgs['Zookd SAs'])\n >>> Zookd_Devs_id = registry.getId(orgs['Zookd Devs'])\n >>> catalog.tokenizeQuery(\n ... {None: zc.relation.catalog.any(\n ... orgs['Zookd SAs'], orgs['Zookd Devs'])}) == {\n ... None: zc.relation.catalog.any(Zookd_SAs_id, Zookd_Devs_id)}\n True\n\nOf course, right now doing this with 'part' alone is kind of silly, since it\ndoes not change within the relation catalog (because we said that dump and\nload were `None`, as discussed above).\n\n >>> catalog.tokenizeQuery({'part': Ynod_SAs_id}) == {\n ... 'part': Ynod_SAs_id}\n True\n >>> catalog.tokenizeQuery(\n ... {'part': zc.relation.catalog.any(Zookd_SAs_id, Zookd_Devs_id)}\n ... ) == {'part': zc.relation.catalog.any(Zookd_SAs_id, Zookd_Devs_id)}\n True\n\nThe `tokenizeQuery` method is so common that we're going to assign it to\na variable in our example. Then we'll do a search or two.\n\nSo...find the relations that Ynod Devs supervise.\n\n >>> t = catalog.tokenizeQuery\n >>> res = list(catalog.findRelationTokens(t({None: orgs['Ynod Devs']})))\n\nOK...we used `findRelationTokens`, as opposed to `findRelations`, so res\nis a couple of numbers now. How do we convert them back?\n`resolveRelationTokens` will do the trick.\n\n >>> len(res)\n 3\n >>> sorted(catalog.resolveRelationTokens(res))\n ... # doctest: +NORMALIZE_WHITESPACE\n [, ,\n ]\n\n`resolveQuery` is the mirror image of `tokenizeQuery`: it converts\ntokenized queries to queries with \"loaded\" values.\n\n >>> original = {'part': zc.relation.catalog.any(\n ... Zookd_SAs_id, Zookd_Devs_id),\n ... None: orgs['Zookd Devs']}\n >>> tokenized = catalog.tokenizeQuery(original)\n >>> original == catalog.resolveQuery(tokenized)\n True\n\n >>> original = {None: zc.relation.catalog.any(\n ... orgs['Zookd SAs'], orgs['Zookd Devs']),\n ... 'part': Zookd_Devs_id}\n >>> tokenized = catalog.tokenizeQuery(original)\n >>> original == catalog.resolveQuery(tokenized)\n True\n\nLikewise, `tokenizeRelations` is the mirror image of `resolveRelationTokens`.\n\n >>> sorted(catalog.tokenizeRelations(\n ... [orgs[\"Bet Proj\"], orgs[\"Y3L4 Proj\"]])) == sorted(\n ... registry.getId(o) for o in\n ... [orgs[\"Bet Proj\"], orgs[\"Y3L4 Proj\"]])\n True\n\nThe other token-related methods are as follows\n[#show_remaining_token_methods]_:\n\n.. [#show_remaining_token_methods] For what it's worth, here are some small\n examples of the remaining token-related methods.\n\n These two are the singular versions of `tokenizeRelations` and\n `resolveRelationTokens`.\n\n `tokenizeRelation` returns a token for the given relation.\n\n >>> catalog.tokenizeRelation(orgs['Zookd Corp Management']) == (\n ... registry.getId(orgs['Zookd Corp Management']))\n True\n\n `resolveRelationToken` returns a relation for the given token.\n\n >>> catalog.resolveRelationToken(registry.getId(\n ... orgs['Zookd Corp Management'])) is orgs['Zookd Corp Management']\n True\n\n The \"values\" ones are a bit lame to show now, since the only value\n we have right now is not tokenized but used straight up. But here\n goes, showing some fascinating no-ops.\n\n `tokenizeValues`, returns an iterable of tokens for the values of\n the given index name.\n\n >>> list(catalog.tokenizeValues((1,2,3), 'part'))\n [1, 2, 3]\n\n `resolveValueTokens` returns an iterable of values for the tokens of\n the given index name.\n\n >>> list(catalog.resolveValueTokens((1,2,3), 'part'))\n [1, 2, 3]\n\n\n- `tokenizeValues`, which returns an iterable of tokens for the values\n of the given index name;\n- `resolveValueTokens`, which returns an iterable of values for the tokens of\n the given index name;\n- `tokenizeRelation`, which returns a token for the given relation; and\n- `resolveRelationToken`, which returns a relation for the given token.\n\nWhy do we bother with these tokens, instead of hiding them away and\nmaking the API prettier? By exposing them, we enable efficient joining,\nand efficient use in other contexts. For instance, if you use the same\nintid utility to tokenize in other catalogs, our results can be merged\nwith the results of other catalogs. Similarly, you can use the results\nof queries to other catalogs--or even \"joins\" from earlier results of\nquerying this catalog--as query values here. We'll explore this in the\nnext section.\n\nRoles\n=====\n\nWe have set up the Organization relations. Now let's set up the roles, and\nactually be able to answer the questions that we described at the beginning\nof the document.\n\nIn our Roles object, roles and principals will simply be strings--ids, if\nthis were a real system. The organization will be a direct object reference.\n\n >>> @zope.interface.implementer(IRoles)\n ... @total_ordering\n ... class Roles(persistent.Persistent):\n ...\n ... def __init__(self, principal_id, role_ids, organization):\n ... self.principal_id = principal_id\n ... self.role_ids = BTrees.family32.OI.TreeSet(role_ids)\n ... self._organization = organization\n ... def getOrganization(self):\n ... return self._organization\n ... # the rest is for prettier/easier tests\n ... def __repr__(self):\n ... return \"\" % (\n ... self.principal_id, ', '.join(self.role_ids),\n ... self._organization.title)\n ... def __lt__(self, other):\n ... _self = (\n ... self.principal_id,\n ... tuple(self.role_ids),\n ... self._organization.title,\n ... )\n ... _other = (\n ... other.principal_id,\n ... tuple(other.role_ids),\n ... other._organization.title,\n ... )\n ... return _self <_other\n ... def __eq__(self, other):\n ... return self is other\n ... def __hash__(self):\n ... return 1 # dummy\n ...\n\nNow let's add add the value indexes to the relation catalog.\n\n >>> catalog.addValueIndex(IRoles['principal_id'], btree=BTrees.family32.OI)\n >>> catalog.addValueIndex(IRoles['role_ids'], btree=BTrees.family32.OI,\n ... multiple=True, name='role_id')\n >>> catalog.addValueIndex(IRoles['getOrganization'], dump, load,\n ... name='organization')\n\nThose are some slightly new variations of what we've seen in `addValueIndex`\nbefore, but all mixing and matching on the same ingredients.\n\nAs a reminder, here is our organization structure::\n\n Ynod Corp Mangement Zookd Corp Management\n / | \\ / | \\\n Ynod Devs Ynod SAs Ynod Admins Zookd Admins Zookd SAs Zookd Devs\n / \\ \\ / / \\\n Y3L4 Proj Bet Proj Ynod Zookd Task Force Zookd hOgnmd Zookd Nbd\n\nNow let's create and add some roles.\n\n >>> principal_ids = [\n ... 'abe', 'bran', 'cathy', 'david', 'edgar', 'frank', 'gertrude',\n ... 'harriet', 'ignas', 'jacob', 'karyn', 'lettie', 'molly', 'nancy',\n ... 'ophelia', 'pat']\n >>> role_ids = ['user manager', 'writer', 'reviewer', 'publisher']\n >>> get_role = dict((v[0], v) for v in role_ids).__getitem__\n >>> roles = root['roles'] = BTrees.family32.IO.BTree()\n >>> next = 0\n >>> for prin, org, role_ids in (\n ... ('abe', orgs['Zookd Corp Management'], 'uwrp'),\n ... ('bran', orgs['Ynod Corp Management'], 'uwrp'),\n ... ('cathy', orgs['Ynod Devs'], 'w'),\n ... ('cathy', orgs['Y3L4 Proj'], 'r'),\n ... ('david', orgs['Bet Proj'], 'wrp'),\n ... ('edgar', orgs['Ynod Devs'], 'up'),\n ... ('frank', orgs['Ynod SAs'], 'uwrp'),\n ... ('frank', orgs['Ynod Admins'], 'w'),\n ... ('gertrude', orgs['Ynod Zookd Task Force'], 'uwrp'),\n ... ('harriet', orgs['Ynod Zookd Task Force'], 'w'),\n ... ('harriet', orgs['Ynod Admins'], 'r'),\n ... ('ignas', orgs['Zookd Admins'], 'r'),\n ... ('ignas', orgs['Zookd Corp Management'], 'w'),\n ... ('karyn', orgs['Zookd Corp Management'], 'uwrp'),\n ... ('karyn', orgs['Ynod Corp Management'], 'uwrp'),\n ... ('lettie', orgs['Zookd Corp Management'], 'u'),\n ... ('lettie', orgs['Ynod Zookd Task Force'], 'w'),\n ... ('lettie', orgs['Zookd SAs'], 'w'),\n ... ('molly', orgs['Zookd SAs'], 'uwrp'),\n ... ('nancy', orgs['Zookd Devs'], 'wrp'),\n ... ('nancy', orgs['Zookd hOgnmd'], 'u'),\n ... ('ophelia', orgs['Zookd Corp Management'], 'w'),\n ... ('ophelia', orgs['Zookd Devs'], 'r'),\n ... ('ophelia', orgs['Zookd Nbd'], 'p'),\n ... ('pat', orgs['Zookd Nbd'], 'wrp')):\n ... assert prin in principal_ids\n ... role_ids = [get_role(l) for l in role_ids]\n ... role = roles[next] = Roles(prin, role_ids, org)\n ... role.key = next\n ... next += 1\n ... catalog.index(role)\n ...\n\nNow we can begin to do searches [#real_value_tokens]_.\n\n\n.. [#real_value_tokens] We can also show the values token methods more\n sanely now.\n\n >>> original = sorted((orgs['Zookd Devs'], orgs['Ynod SAs']))\n >>> tokens = list(catalog.tokenizeValues(original, 'organization'))\n >>> original == sorted(catalog.resolveValueTokens(tokens, 'organization'))\n True\n\nWhat are all the role settings for ophelia?\n\n >>> sorted(catalog.findRelations({'principal_id': 'ophelia'}))\n ... # doctest: +NORMALIZE_WHITESPACE\n [,\n ,\n ]\n\nThat answer does not need to be transitive: we're done.\n\nNext question. Where does ophelia have the 'writer' role?\n\n >>> list(catalog.findValues(\n ... 'organization', {'principal_id': 'ophelia',\n ... 'role_id': 'writer'}))\n []\n\nWell, that's correct intransitively. Do we need a transitive queries\nfactory? No! This is a great chance to look at the token join we talked\nabout in the previous section. This should actually be a two-step\noperation: find all of the organizations in which ophelia has writer,\nand then find all of the transitive parts to that organization.\n\n >>> sorted(catalog.findRelations({None: zc.relation.catalog.Any(\n ... catalog.findValueTokens('organization',\n ... {'principal_id': 'ophelia',\n ... 'role_id': 'writer'}))}))\n ... # doctest: +NORMALIZE_WHITESPACE\n [,\n ,\n ,\n ,\n ,\n ,\n ]\n\nThat's more like it.\n\nNext question. What users have roles in the 'Zookd Devs' organization?\nIntransitively, that's pretty easy.\n\n >>> sorted(catalog.findValueTokens(\n ... 'principal_id', t({'organization': orgs['Zookd Devs']})))\n ['nancy', 'ophelia']\n\nTransitively, we should do another join.\n\n >>> org_id = registry.getId(orgs['Zookd Devs'])\n >>> sorted(catalog.findValueTokens(\n ... 'principal_id', {\n ... 'organization': zc.relation.catalog.any(\n ... org_id, *catalog.findRelationTokens({'part': org_id}))}))\n ['abe', 'ignas', 'karyn', 'lettie', 'nancy', 'ophelia']\n\nThat's a little awkward, but it does the trick.\n\nLast question, and the kind of question that started the entire example.\n What roles does ophelia have in the \"Zookd Nbd\" organization?\n\n >>> list(catalog.findValueTokens(\n ... 'role_id', t({'organization': orgs['Zookd Nbd'],\n ... 'principal_id': 'ophelia'})))\n ['publisher']\n\nIntransitively, that's correct. But, transitively, ophelia also has\nreviewer and writer, and that's the answer we want to be able to get quickly.\n\nWe could ask the question a different way, then, again leveraging a join.\nWe'll set it up as a function, because we will want to use it a little later\nwithout repeating the code.\n\n >>> def getRolesInOrganization(principal_id, org):\n ... org_id = registry.getId(org)\n ... return sorted(catalog.findValueTokens(\n ... 'role_id', {\n ... 'organization': zc.relation.catalog.any(\n ... org_id,\n ... *catalog.findRelationTokens({'part': org_id})),\n ... 'principal_id': principal_id}))\n ...\n >>> getRolesInOrganization('ophelia', orgs['Zookd Nbd'])\n ['publisher', 'reviewer', 'writer']\n\nAs you can see, then, working with tokens makes interesting joins possible,\nas long as the tokens are the same across the two queries.\n\nWe have examined tokens methods and token techniques like joins. The example\nstory we have told can let us get into a few more advanced topics, such as\nquery factory joins and search indexes that can increase their read speed.\n\nQuery Factory Joins\n===================\n\nWe can build a query factory that makes the join automatic. A query\nfactory is a callable that takes two arguments: a query (the one that\nstarts the search) and the catalog. The factory either returns None,\nindicating that the query factory cannot be used for this query, or it\nreturns another callable that takes a chain of relations. The last\ntoken in the relation chain is the most recent. The output of this\ninner callable is expected to be an iterable of\nBTrees.family32.OO.Bucket queries to search further from the given chain\nof relations.\n\nHere's a flawed approach to this problem.\n\n >>> def flawed_factory(query, catalog):\n ... if (len(query) == 2 and\n ... 'organization' in query and\n ... 'principal_id' in query):\n ... def getQueries(relchain):\n ... if not relchain:\n ... yield query\n ... return\n ... current = catalog.getValueTokens(\n ... 'organization', relchain[-1])\n ... if current:\n ... organizations = catalog.getRelationTokens(\n ... {'part': zc.relation.catalog.Any(current)})\n ... if organizations:\n ... res = BTrees.family32.OO.Bucket(query)\n ... res['organization'] = zc.relation.catalog.Any(\n ... organizations)\n ... yield res\n ... return getQueries\n ...\n\nThat works for our current example.\n\n >>> sorted(catalog.findValueTokens(\n ... 'role_id', t({'organization': orgs['Zookd Nbd'],\n ... 'principal_id': 'ophelia'}),\n ... queryFactory=flawed_factory))\n ['publisher', 'reviewer', 'writer']\n\nHowever, it won't work for other similar queries.\n\n >>> getRolesInOrganization('abe', orgs['Zookd Nbd'])\n ['publisher', 'reviewer', 'user manager', 'writer']\n >>> sorted(catalog.findValueTokens(\n ... 'role_id', t({'organization': orgs['Zookd Nbd'],\n ... 'principal_id': 'abe'}),\n ... queryFactory=flawed_factory))\n []\n\noops.\n\nThe flawed_factory is actually a useful pattern for more typical relation\ntraversal. It goes from relation to relation to relation, and ophelia has\nconnected relations all the way to the top. However, abe only has them at\nthe top, so nothing is traversed.\n\nInstead, we can make a query factory that modifies the initial query.\n\n >>> def factory2(query, catalog):\n ... if (len(query) == 2 and\n ... 'organization' in query and\n ... 'principal_id' in query):\n ... def getQueries(relchain):\n ... if not relchain:\n ... res = BTrees.family32.OO.Bucket(query)\n ... org_id = query['organization']\n ... if org_id is not None:\n ... res['organization'] = zc.relation.catalog.any(\n ... org_id,\n ... *catalog.findRelationTokens({'part': org_id}))\n ... yield res\n ... return getQueries\n ...\n\n >>> sorted(catalog.findValueTokens(\n ... 'role_id', t({'organization': orgs['Zookd Nbd'],\n ... 'principal_id': 'ophelia'}),\n ... queryFactory=factory2))\n ['publisher', 'reviewer', 'writer']\n\n >>> sorted(catalog.findValueTokens(\n ... 'role_id', t({'organization': orgs['Zookd Nbd'],\n ... 'principal_id': 'abe'}),\n ... queryFactory=factory2))\n ['publisher', 'reviewer', 'user manager', 'writer']\n\nA difference between this and the other approach is that it is essentially\nintransitive: this query factory modifies the initial query, and then does\nnot give further queries. The catalog currently always stops calling the\nquery factory if the queries do not return any results, so an approach like\nthe flawed_factory simply won't work for this kind of problem.\n\nWe could add this query factory as another default.\n\n >>> catalog.addDefaultQueryFactory(factory2)\n\n >>> sorted(catalog.findValueTokens(\n ... 'role_id', t({'organization': orgs['Zookd Nbd'],\n ... 'principal_id': 'ophelia'})))\n ['publisher', 'reviewer', 'writer']\n\n >>> sorted(catalog.findValueTokens(\n ... 'role_id', t({'organization': orgs['Zookd Nbd'],\n ... 'principal_id': 'abe'})))\n ['publisher', 'reviewer', 'user manager', 'writer']\n\nThe previously installed query factory is still available.\n\n >>> list(catalog.iterDefaultQueryFactories()) == [factory1, factory2]\n True\n\n >>> list(catalog.findRelations(\n ... {'part': registry.getId(orgs['Y3L4 Proj'])}))\n ... # doctest: +NORMALIZE_WHITESPACE\n [,\n ]\n\n >>> sorted(catalog.findRelations(\n ... {None: registry.getId(orgs['Ynod Corp Management'])}))\n ... # doctest: +NORMALIZE_WHITESPACE\n [, ,\n ,\n ,\n , ,\n ]\n\nSearch Index for Query Factory Joins\n====================================\n\nNow that we have written a query factory that encapsulates the join, we can\nuse a search index that speeds it up. We've only used transitive search\nindexes so far. Now we will add an intransitive search index.\n\nThe intransitive search index generally just needs the search value\nnames it should be indexing, optionally the result name (defaulting to\nrelations), and optionally the query factory to be used.\n\nWe need to use two additional options because of the odd join trick we're\ndoing. We need to specify what organization and principal_id values need\nto be changed when an object is indexed, and we need to indicate that we\nshould update when organization, principal_id, *or* parts changes.\n\n`getValueTokens` specifies the values that need to be indexed. It gets\nthe index, the name for the tokens desired, the token, the catalog that\ngenerated the token change (it may not be the same as the index's\ncatalog, the source dictionary that contains a dictionary of the values\nthat will be used for tokens if you do not override them, a dict of the\nadded values for this token (keys are value names), a dict of the\nremoved values for this token, and whether the token has been removed.\nThe method can return None, which will leave the index to its default\nbehavior that should work if no query factory is used; or an iterable of\nvalues.\n\n >>> def getValueTokens(index, name, token, catalog, source,\n ... additions, removals, removed):\n ... if name == 'organization':\n ... orgs = source.get('organization')\n ... if not removed or not orgs:\n ... orgs = index.catalog.getValueTokens(\n ... 'organization', token)\n ... if not orgs:\n ... orgs = [token]\n ... orgs.extend(removals.get('part', ()))\n ... orgs = set(orgs)\n ... orgs.update(index.catalog.findValueTokens(\n ... 'part',\n ... {None: zc.relation.catalog.Any(\n ... t for t in orgs if t is not None)}))\n ... return orgs\n ... elif name == 'principal_id':\n ... # we only want custom behavior if this is an organization\n ... if 'principal_id' in source or index.catalog.getValueTokens(\n ... 'principal_id', token):\n ... return ''\n ... orgs = set((token,))\n ... orgs.update(index.catalog.findRelationTokens(\n ... {'part': token}))\n ... return set(index.catalog.findValueTokens(\n ... 'principal_id', {\n ... 'organization': zc.relation.catalog.Any(orgs)}))\n ...\n\n >>> index = zc.relation.searchindex.Intransitive(\n ... ('organization', 'principal_id'), 'role_id', factory2,\n ... getValueTokens,\n ... ('organization', 'principal_id', 'part', 'role_id'),\n ... unlimitedDepth=True)\n >>> catalog.addSearchIndex(index)\n\n >>> res = catalog.findValueTokens(\n ... 'role_id', t({'organization': orgs['Zookd Nbd'],\n ... 'principal_id': 'ophelia'}))\n >>> list(res)\n ['publisher', 'reviewer', 'writer']\n >>> list(res)\n ['publisher', 'reviewer', 'writer']\n\n >>> res = catalog.findValueTokens(\n ... 'role_id', t({'organization': orgs['Zookd Nbd'],\n ... 'principal_id': 'abe'}))\n >>> list(res)\n ['publisher', 'reviewer', 'user manager', 'writer']\n >>> list(res)\n ['publisher', 'reviewer', 'user manager', 'writer']\n\n[#verifyObjectIntransitive]_\n\n.. [#verifyObjectIntransitive] The Intransitive search index provides\n ISearchIndex and IListener.\n\n >>> from zope.interface.verify import verifyObject\n >>> import zc.relation.interfaces\n >>> verifyObject(zc.relation.interfaces.ISearchIndex, index)\n True\n >>> verifyObject(zc.relation.interfaces.IListener, index)\n True\n\nNow we can change and remove relations--both organizations and roles--and\nhave the index maintain correct state. Given the current state of\norganizations--\n\n::\n\n Ynod Corp Mangement Zookd Corp Management\n / | \\ / | \\\n Ynod Devs Ynod SAs Ynod Admins Zookd Admins Zookd SAs Zookd Devs\n / \\ \\ / / \\\n Y3L4 Proj Bet Proj Ynod Zookd Task Force Zookd hOgnmd Zookd Nbd\n\n--first we will move Ynod Devs to beneath Zookd Devs, and back out. This will\nbriefly give abe full privileges to Y3L4 Proj., among others.\n\n >>> list(catalog.findValueTokens(\n ... 'role_id', t({'organization': orgs['Y3L4 Proj'],\n ... 'principal_id': 'abe'})))\n []\n >>> orgs['Zookd Devs'].parts.insert(registry.getId(orgs['Ynod Devs']))\n 1\n >>> catalog.index(orgs['Zookd Devs'])\n >>> res = catalog.findValueTokens(\n ... 'role_id', t({'organization': orgs['Y3L4 Proj'],\n ... 'principal_id': 'abe'}))\n >>> list(res)\n ['publisher', 'reviewer', 'user manager', 'writer']\n >>> list(res)\n ['publisher', 'reviewer', 'user manager', 'writer']\n >>> orgs['Zookd Devs'].parts.remove(registry.getId(orgs['Ynod Devs']))\n >>> catalog.index(orgs['Zookd Devs'])\n >>> list(catalog.findValueTokens(\n ... 'role_id', t({'organization': orgs['Y3L4 Proj'],\n ... 'principal_id': 'abe'})))\n []\n\nAs another example, we will change the roles abe has, and see that it is\npropagated down to Zookd Nbd.\n\n >>> rels = list(catalog.findRelations(t(\n ... {'principal_id': 'abe',\n ... 'organization': orgs['Zookd Corp Management']})))\n >>> len(rels)\n 1\n >>> rels[0].role_ids.remove('reviewer')\n >>> catalog.index(rels[0])\n\n >>> res = catalog.findValueTokens(\n ... 'role_id', t({'organization': orgs['Zookd Nbd'],\n ... 'principal_id': 'abe'}))\n >>> list(res)\n ['publisher', 'user manager', 'writer']\n >>> list(res)\n ['publisher', 'user manager', 'writer']\n\nNote that search index order matters. In our case, our intransitive search\nindex is relying on our transitive index, so the transitive index needs to\ncome first. You want transitive relation indexes before name. Right now,\nyou are in charge of this order: it will be difficult to come up with a\nreliable algorithm for guessing this.\n\nListeners, Catalog Administration, and Joining Across Relation Catalogs\n=======================================================================\n\nWe've done all of our examples so far with a single catalog that indexes\nboth kinds of relations. What if we want to have two catalogs with\nhomogenous collections of relations? That can feel cleaner, but it also\nintroduces some new wrinkles.\n\nLet's use our current catalog for organizations, removing the extra\ninformation; and create a new one for roles.\n\n >>> role_catalog = root['role_catalog'] = catalog.copy()\n >>> transaction.commit()\n >>> org_catalog = catalog\n >>> del catalog\n\nWe'll need a slightly different query factory and a slightly different\nsearch index `getValueTokens` function. We'll write those, then modify the\nconfiguration of our two catalogs for the new world.\n\nThe transitive factory we write here is for the role catalog. It needs\naccess to the organzation catalog. We could do this a variety of\nways--relying on a utility, or finding the catalog from context. We will\nmake the role_catalog have a .org_catalog attribute, and rely on that.\n\n >>> role_catalog.org_catalog = org_catalog\n >>> def factory3(query, catalog):\n ... if (len(query) == 2 and\n ... 'organization' in query and\n ... 'principal_id' in query):\n ... def getQueries(relchain):\n ... if not relchain:\n ... res = BTrees.family32.OO.Bucket(query)\n ... org_id = query['organization']\n ... if org_id is not None:\n ... res['organization'] = zc.relation.catalog.any(\n ... org_id,\n ... *catalog.org_catalog.findRelationTokens(\n ... {'part': org_id}))\n ... yield res\n ... return getQueries\n ...\n\n >>> def getValueTokens2(index, name, token, catalog, source,\n ... additions, removals, removed):\n ... is_role_catalog = catalog is index.catalog # role_catalog\n ... if name == 'organization':\n ... if is_role_catalog:\n ... orgs = set(source.get('organization') or\n ... index.catalog.getValueTokens(\n ... 'organization', token) or ())\n ... else:\n ... orgs = set((token,))\n ... orgs.update(removals.get('part', ()))\n ... orgs.update(index.catalog.org_catalog.findValueTokens(\n ... 'part',\n ... {None: zc.relation.catalog.Any(\n ... t for t in orgs if t is not None)}))\n ... return orgs\n ... elif name == 'principal_id':\n ... # we only want custom behavior if this is an organization\n ... if not is_role_catalog:\n ... orgs = set((token,))\n ... orgs.update(index.catalog.org_catalog.findRelationTokens(\n ... {'part': token}))\n ... return set(index.catalog.findValueTokens(\n ... 'principal_id', {\n ... 'organization': zc.relation.catalog.Any(orgs)}))\n ... return ''\n\nIf you are following along in the code and comparing to the originals, you may\nsee that this approach is a bit cleaner than the one when the relations were\nin the same catalog.\n\nNow we will fix up the the organization catalog [#compare_copy]_.\n\n.. [#compare_copy] Before we modify them, let's look at the copy we made.\n The copy should currently behave identically to the original.\n\n >>> len(org_catalog)\n 38\n >>> len(role_catalog)\n 38\n >>> indexed = list(org_catalog)\n >>> len(indexed)\n 38\n >>> orgs['Zookd Devs'] in indexed\n True\n >>> for r in indexed:\n ... if r not in role_catalog:\n ... print('bad')\n ... break\n ... else:\n ... print('good')\n ...\n good\n >>> org_names = set(dir(org_catalog))\n >>> role_names = set(dir(role_catalog))\n >>> sorted(org_names - role_names)\n []\n >>> sorted(role_names - org_names)\n ['org_catalog']\n\n >>> def checkYnodDevsParts(catalog):\n ... res = sorted(catalog.findRelations(t({None: orgs['Ynod Devs']})))\n ... if res != [\n ... orgs[\"Bet Proj\"], orgs[\"Y3L4 Proj\"], orgs[\"Ynod Devs\"]]:\n ... print(\"bad\", res)\n ...\n >>> checkYnodDevsParts(org_catalog)\n >>> checkYnodDevsParts(role_catalog)\n\n >>> def checkOpheliaRoles(catalog):\n ... res = sorted(catalog.findRelations({'principal_id': 'ophelia'}))\n ... if repr(res) != (\n ... \"[, \" +\n ... \", \" +\n ... \"]\"):\n ... print(\"bad\", res)\n ...\n >>> checkOpheliaRoles(org_catalog)\n >>> checkOpheliaRoles(role_catalog)\n\n >>> def checkOpheliaWriterOrganizations(catalog):\n ... res = sorted(catalog.findRelations({None: zc.relation.catalog.Any(\n ... catalog.findValueTokens(\n ... 'organization', {'principal_id': 'ophelia',\n ... 'role_id': 'writer'}))}))\n ... if repr(res) != (\n ... '[, ' +\n ... ', ' +\n ... ', ' +\n ... ', ' +\n ... ', ' +\n ... ', ' +\n ... ']'):\n ... print(\"bad\", res)\n ...\n >>> checkOpheliaWriterOrganizations(org_catalog)\n >>> checkOpheliaWriterOrganizations(role_catalog)\n\n >>> def checkPrincipalsWithRolesInZookdDevs(catalog):\n ... org_id = registry.getId(orgs['Zookd Devs'])\n ... res = sorted(catalog.findValueTokens(\n ... 'principal_id',\n ... {'organization': zc.relation.catalog.any(\n ... org_id, *catalog.findRelationTokens({'part': org_id}))}))\n ... if res != ['abe', 'ignas', 'karyn', 'lettie', 'nancy', 'ophelia']:\n ... print(\"bad\", res)\n ...\n >>> checkPrincipalsWithRolesInZookdDevs(org_catalog)\n >>> checkPrincipalsWithRolesInZookdDevs(role_catalog)\n\n >>> def checkOpheliaRolesInZookdNbd(catalog):\n ... res = sorted(catalog.findValueTokens(\n ... 'role_id', {\n ... 'organization': registry.getId(orgs['Zookd Nbd']),\n ... 'principal_id': 'ophelia'}))\n ... if res != ['publisher', 'reviewer', 'writer']:\n ... print(\"bad\", res)\n ...\n >>> checkOpheliaRolesInZookdNbd(org_catalog)\n >>> checkOpheliaRolesInZookdNbd(role_catalog)\n\n >>> def checkAbeRolesInZookdNbd(catalog):\n ... res = sorted(catalog.findValueTokens(\n ... 'role_id', {\n ... 'organization': registry.getId(orgs['Zookd Nbd']),\n ... 'principal_id': 'abe'}))\n ... if res != ['publisher', 'user manager', 'writer']:\n ... print(\"bad\", res)\n ...\n >>> checkAbeRolesInZookdNbd(org_catalog)\n >>> checkAbeRolesInZookdNbd(role_catalog)\n >>> org_catalog.removeDefaultQueryFactory(None) # doctest: +ELLIPSIS\n Traceback (most recent call last):\n ...\n LookupError: ('factory not found', None)\n\n >>> org_catalog.removeValueIndex('organization')\n >>> org_catalog.removeValueIndex('role_id')\n >>> org_catalog.removeValueIndex('principal_id')\n >>> org_catalog.removeDefaultQueryFactory(factory2)\n >>> org_catalog.removeSearchIndex(index)\n >>> org_catalog.clear()\n >>> len(org_catalog)\n 0\n >>> for v in orgs.values():\n ... org_catalog.index(v)\n\nThis also shows using the `removeDefaultQueryFactory` and `removeSearchIndex`\nmethods [#removeDefaultQueryFactoryExceptions]_.\n\n.. [#removeDefaultQueryFactoryExceptions] You get errors by removing query\n factories that are not registered.\n\n >>> org_catalog.removeDefaultQueryFactory(factory2) # doctest: +ELLIPSIS\n Traceback (most recent call last):\n ...\n LookupError: ('factory not found', )\n\nNow we will set up the role catalog [#copy_unchanged]_.\n\n\n.. [#copy_unchanged] Changes to one copy should not affect the other. That\n means the role_catalog should still work as before.\n\n >>> len(org_catalog)\n 13\n >>> len(list(org_catalog))\n 13\n\n >>> len(role_catalog)\n 38\n >>> indexed = list(role_catalog)\n >>> len(indexed)\n 38\n >>> orgs['Zookd Devs'] in indexed\n True\n >>> orgs['Zookd Devs'] in role_catalog\n True\n\n >>> checkYnodDevsParts(role_catalog)\n >>> checkOpheliaRoles(role_catalog)\n >>> checkOpheliaWriterOrganizations(role_catalog)\n >>> checkPrincipalsWithRolesInZookdDevs(role_catalog)\n >>> checkOpheliaRolesInZookdNbd(role_catalog)\n >>> checkAbeRolesInZookdNbd(role_catalog)\n\n >>> role_catalog.removeValueIndex('part')\n >>> for ix in list(role_catalog.iterSearchIndexes()):\n ... role_catalog.removeSearchIndex(ix)\n ...\n >>> role_catalog.removeDefaultQueryFactory(factory1)\n >>> role_catalog.removeDefaultQueryFactory(factory2)\n >>> role_catalog.addDefaultQueryFactory(factory3)\n >>> root['index2'] = index2 = zc.relation.searchindex.Intransitive(\n ... ('organization', 'principal_id'), 'role_id', factory3,\n ... getValueTokens2,\n ... ('organization', 'principal_id', 'part', 'role_id'),\n ... unlimitedDepth=True)\n >>> role_catalog.addSearchIndex(index2)\n\nThe new role_catalog index needs to be updated from the org_catalog.\nWe'll set that up using listeners, a new concept.\n\n >>> org_catalog.addListener(index2)\n >>> list(org_catalog.iterListeners()) == [index2]\n True\n\nNow the role_catalog should be able to answer the same questions as the old\nsingle catalog approach.\n\n >>> t = role_catalog.tokenizeQuery\n >>> list(role_catalog.findValueTokens(\n ... 'role_id', t({'organization': orgs['Zookd Nbd'],\n ... 'principal_id': 'abe'})))\n ['publisher', 'user manager', 'writer']\n\n >>> list(role_catalog.findValueTokens(\n ... 'role_id', t({'organization': orgs['Zookd Nbd'],\n ... 'principal_id': 'ophelia'})))\n ['publisher', 'reviewer', 'writer']\n\nWe can also make changes to both catalogs and the search indexes are\nmaintained.\n\n >>> list(role_catalog.findValueTokens(\n ... 'role_id', t({'organization': orgs['Y3L4 Proj'],\n ... 'principal_id': 'abe'})))\n []\n >>> orgs['Zookd Devs'].parts.insert(registry.getId(orgs['Ynod Devs']))\n 1\n >>> org_catalog.index(orgs['Zookd Devs'])\n >>> list(role_catalog.findValueTokens(\n ... 'role_id', t({'organization': orgs['Y3L4 Proj'],\n ... 'principal_id': 'abe'})))\n ['publisher', 'user manager', 'writer']\n >>> orgs['Zookd Devs'].parts.remove(registry.getId(orgs['Ynod Devs']))\n >>> org_catalog.index(orgs['Zookd Devs'])\n >>> list(role_catalog.findValueTokens(\n ... 'role_id', t({'organization': orgs['Y3L4 Proj'],\n ... 'principal_id': 'abe'})))\n []\n\n >>> rels = list(role_catalog.findRelations(t(\n ... {'principal_id': 'abe',\n ... 'organization': orgs['Zookd Corp Management']})))\n >>> len(rels)\n 1\n >>> rels[0].role_ids.insert('reviewer')\n 1\n >>> role_catalog.index(rels[0])\n\n >>> res = role_catalog.findValueTokens(\n ... 'role_id', t({'organization': orgs['Zookd Nbd'],\n ... 'principal_id': 'abe'}))\n >>> list(res)\n ['publisher', 'reviewer', 'user manager', 'writer']\n\nHere we add a new organization.\n\n >>> orgs['Zookd hOnc'] = org = Organization('Zookd hOnc')\n >>> orgs['Zookd Devs'].parts.insert(registry.getId(org))\n 1\n >>> org_catalog.index(orgs['Zookd hOnc'])\n >>> org_catalog.index(orgs['Zookd Devs'])\n\n >>> list(role_catalog.findValueTokens(\n ... 'role_id', t({'organization': orgs['Zookd hOnc'],\n ... 'principal_id': 'abe'})))\n ['publisher', 'reviewer', 'user manager', 'writer']\n\n >>> list(role_catalog.findValueTokens(\n ... 'role_id', t({'organization': orgs['Zookd hOnc'],\n ... 'principal_id': 'ophelia'})))\n ['reviewer', 'writer']\n\nNow we'll remove it.\n\n >>> orgs['Zookd Devs'].parts.remove(registry.getId(org))\n >>> org_catalog.index(orgs['Zookd Devs'])\n >>> org_catalog.unindex(orgs['Zookd hOnc'])\n\nTODO make sure that intransitive copy looks the way we expect\n\n[#administrivia]_\n\n.. [#administrivia]\n\n You can add listeners multiple times.\n\n >>> org_catalog.addListener(index2)\n >>> list(org_catalog.iterListeners()) == [index2, index2]\n True\n\n Now we will remove the listeners, to show we can.\n\n >>> org_catalog.removeListener(index2)\n >>> org_catalog.removeListener(index2)\n >>> org_catalog.removeListener(index2)\n ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE\n Traceback (most recent call last):\n ...\n LookupError: ('listener not found',\n )\n >>> org_catalog.removeListener(None)\n ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE\n Traceback (most recent call last):\n ...\n LookupError: ('listener not found', None)\n\n Here's the same for removing a search index we don't have\n\n >>> org_catalog.removeSearchIndex(index2)\n ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE\n Traceback (most recent call last):\n ...\n LookupError: ('index not found',\n )\n\n.. ......... ..\n.. Footnotes ..\n.. ......... ..\n\n\n.. [#silliness] In \"2001: A Space Odyssey\", many people believe the name HAL\n was chosen because it was ROT25 of IBM.... I cheat a bit sometimes and\n use ROT1 because the result sounds better.\n\n\n=================================================================\nWorking with Search Indexes: zc.relation Catalog Extended Example\n=================================================================\n\nIntroduction\n============\n\nThis document assumes you have read the README.rst document, and want to learn\na bit more by example. In it, we will explore a set of relations that\ndemonstrates most of the aspects of working with search indexes and listeners.\nIt will not explain the topics that the other documents already addressed. It\nalso describes an advanced use case.\n\nAs we have seen in the other documents, the relation catalog supports\nsearch indexes. These can return the results of any search, as desired.\nOf course, the intent is that you supply an index that optimizes the\nparticular searches it claims.\n\nThe searchindex module supplies a few search indexes, optimizing\nspecified transitive and intransitive searches. We have seen them working\nin other documents. We will examine them more in depth in this document.\n\nSearch indexes update themselves by receiving messages via a \"listener\"\ninterface. We will also look at how this works.\n\nThe example described in this file examines a use case similar to that in\nthe zc.revision or zc.vault packages: a relation describes a graph of\nother objects. Therefore, this is our first concrete example of purely\nextrinsic relations.\n\nLet's build the example story a bit. Imagine we have a graph, often a\nhierarchy, of tokens--integers. Relations specify that a given integer\ntoken relates to other integer tokens, with a containment denotation or\nother meaning.\n\nThe integers may also have relations that specify that they represent an\nobject or objects.\n\nThis allows us to have a graph of objects in which changing one part of the\ngraph does not require changing the rest. zc.revision and zc.vault thus\nare able to model graphs that can have multiple revisions efficiently and\nwith quite a bit of metadata to support merges.\n\nLet's imagine a simple hierarchy. The relation has a `token` attribute\nand a `children` attribute; children point to tokens. Relations will\nidentify themselves with ids.\n\n >>> import BTrees\n >>> relations = BTrees.family64.IO.BTree()\n >>> relations[99] = None # just to give us a start\n\n >>> class Relation(object):\n ... def __init__(self, token, children=()):\n ... self.token = token\n ... self.children = BTrees.family64.IF.TreeSet(children)\n ... self.id = relations.maxKey() + 1\n ... relations[self.id] = self\n ...\n\n >>> def token(rel, self):\n ... return rel.token\n ...\n >>> def children(rel, self):\n ... return rel.children\n ...\n >>> def dumpRelation(obj, index, cache):\n ... return obj.id\n ...\n >>> def loadRelation(token, index, cache):\n ... return relations[token]\n ...\n\nThe standard TransposingTransitiveQueriesFactory will be able to handle this\nquite well, so we'll use that for our index.\n\n >>> import zc.relation.queryfactory\n >>> factory = zc.relation.queryfactory.TransposingTransitive(\n ... 'token', 'children')\n >>> import zc.relation.catalog\n >>> catalog = zc.relation.catalog.Catalog(\n ... dumpRelation, loadRelation, BTrees.family64.IO, BTrees.family64)\n >>> catalog.addValueIndex(token)\n >>> catalog.addValueIndex(children, multiple=True)\n >>> catalog.addDefaultQueryFactory(factory)\n\nNow let's quickly create a hierarchy and index it.\n\n >>> for token, children in (\n ... (0, (1, 2)), (1, (3, 4)), (2, (10, 11, 12)), (3, (5, 6)),\n ... (4, (13, 14)), (5, (7, 8, 9)), (6, (15, 16)), (7, (17, 18, 19)),\n ... (8, (20, 21, 22)), (9, (23, 24)), (10, (25, 26)),\n ... (11, (27, 28, 29, 30, 31, 32))):\n ... catalog.index(Relation(token, children))\n ...\n\n[#queryFactory]_ That hierarchy is arbitrary. Here's what we have, in terms of tokens\npointing to children::\n\n _____________0_____________\n / \\\n ________1_______ ______2____________\n / \\ / | \\\n ______3_____ _4_ 10 ____11_____ 12\n / \\ / \\ / \\ / / | \\ \\ \\\n _______5_______ 6 13 14 25 26 27 28 29 30 31 32\n / | \\ / \\\n _7_ _8_ 9 15 16\n / | \\ / | \\ / \\\n 17 18 19 20 21 22 23 24\n\nTwelve relations, with tokens 0 through 11, and a total of 33 tokens,\nincluding children. The ids for the 12 relations are 100 through 111,\ncorresponding with the tokens of 0 through 11.\n\nWithout a transitive search index, we can get all transitive results.\nThe results are iterators.\n\n >>> res = catalog.findRelationTokens({'token': 0})\n >>> import six\n >>> next_attr = '__next__' if six.PY3 else 'next'\n >>> getattr(res, next_attr) is None\n False\n >>> getattr(res, '__len__', None) is None\n True\n >>> sorted(res)\n [100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111]\n >>> list(res)\n []\n\n >>> res = catalog.findValueTokens('children', {'token': 0})\n >>> sorted(res) == list(range(1, 33))\n True\n >>> list(res)\n []\n\n[#findValuesUnindexed]_ `canFind` also can work transitively, and will\nuse transitive search indexes, as we'll see below.\n\n >>> catalog.canFind({'token': 1}, targetQuery={'children': 23})\n True\n >>> catalog.canFind({'token': 2}, targetQuery={'children': 23})\n False\n >>> catalog.canFind({'children': 23}, targetQuery={'token': 1})\n True\n >>> catalog.canFind({'children': 23}, targetQuery={'token': 2})\n False\n\n`findRelationTokenChains` won't change, but we'll include it in the\ndiscussion and examples to show that.\n\n >>> res = catalog.findRelationTokenChains({'token': 2})\n >>> chains = list(res)\n >>> len(chains)\n 3\n >>> len(list(res))\n 0\n\nTransitive Search Indexes\n=========================\n\nNow we can add a couple of transitive search index. We'll talk about\nthem a bit first.\n\nThere is currently one variety of transitive index, which indexes\nrelation and value searches for the transposing transitive query\nfactory.\n\nThe index can only be used under certain conditions.\n\n - The search is not a request for a relation chain.\n\n - It does not specify a maximum depth.\n\n - Filters are not used.\n\nIf it is a value search, then specific value indexes cannot be used if a\ntarget filter or target query are used, but the basic relation index can\nstill be used in that case.\n\nThe usage of the search indexes is largely transparent: set them up, and\nthe relation catalog will use them for the same API calls that used more\nbrute force previously. The only difference from external uses is that\nresults that use an index will usually be a BTree structure, rather than\nan iterator.\n\nWhen you add a transitive index for a relation, you must specify the\ntransitive name (or names) of the query, and the same for the reverse.\nThat's all we'll do now.\n\n >>> import zc.relation.searchindex\n >>> catalog.addSearchIndex(\n ... zc.relation.searchindex.TransposingTransitiveMembership(\n ... 'token', 'children', names=('children',)))\n\nNow we should have a search index installed.\n\nNotice that we went from parent (token) to child: this index is primarily\ndesigned for helping transitive membership searches in a hierarchy. Using it to\nindex parents would incur a lot of write expense for not much win.\n\nThere's just a bit more you can specify here: static fields for a query\nto do a bit of filtering. We don't need any of that for this example.\n\nNow how does the catalog use this index for searches? Three basic ways,\ndepending on the kind of search, relations, values, or `canFind`.\nBefore we start looking into the internals, let's verify that we're getting\nwhat we expect: correct answers, and not iterators, but BTree structures.\n\n >>> res = catalog.findRelationTokens({'token': 0})\n >>> list(res)\n [100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111]\n >>> list(res)\n [100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111]\n\n >>> res = catalog.findValueTokens('children', {'token': 0})\n >>> list(res) == list(range(1, 33))\n True\n >>> list(res) == list(range(1, 33))\n True\n\n >>> catalog.canFind({'token': 1}, targetQuery={'children': 23})\n True\n >>> catalog.canFind({'token': 2}, targetQuery={'children': 23})\n False\n\n[#findValuesIndexed]_ Note that the last two `canFind` examples from\nwhen we went through these examples without an index do not use the\nindex, so we don't show them here: they look the wrong direction for\nthis index.\n\nSo how do these results happen?\n\nThe first, `findRelationTokens`, and the last, `canFind`, are the most\nstraightforward. The index finds all relations that match the given\nquery, intransitively. Then for each relation, it looks up the indexed\ntransitive results for that token. The end result is the union of all\nindexed results found from the intransitive search. `canFind` simply\ncasts the result into a boolean.\n\n`findValueTokens` is the same story as above with only one more step. After\nthe union of relations is calculated, the method returns the union of the\nsets of the requested value for all found relations.\n\nIt will maintain itself when relations are reindexed.\n\n >>> rel = list(catalog.findRelations({'token': 11}))[0]\n >>> for t in (27, 28, 29, 30, 31):\n ... rel.children.remove(t)\n ...\n >>> catalog.index(rel)\n\n >>> catalog.findValueTokens('children', {'token': 0})\n ... # doctest: +NORMALIZE_WHITESPACE\n LFSet([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,\n 20, 21, 22, 23, 24, 25, 26, 32])\n >>> catalog.findValueTokens('children', {'token': 2})\n LFSet([10, 11, 12, 25, 26, 32])\n >>> catalog.findValueTokens('children', {'token': 11})\n LFSet([32])\n\n >>> rel.children.remove(32)\n >>> catalog.index(rel)\n\n >>> catalog.findValueTokens('children', {'token': 0})\n ... # doctest: +NORMALIZE_WHITESPACE\n LFSet([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,\n 20, 21, 22, 23, 24, 25, 26])\n >>> catalog.findValueTokens('children', {'token': 2})\n LFSet([10, 11, 12, 25, 26])\n >>> catalog.findValueTokens('children', {'token': 11})\n LFSet([])\n\n >>> rel.children.insert(27)\n 1\n >>> catalog.index(rel)\n\n >>> catalog.findValueTokens('children', {'token': 0})\n ... # doctest: +NORMALIZE_WHITESPACE\n LFSet([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,\n 20, 21, 22, 23, 24, 25, 26, 27])\n >>> catalog.findValueTokens('children', {'token': 2})\n LFSet([10, 11, 12, 25, 26, 27])\n >>> catalog.findValueTokens('children', {'token': 11})\n LFSet([27])\n\nWhen the index is copied, the search index is copied.\n\n >>> new = catalog.copy()\n >>> res = list(new.iterSearchIndexes())\n >>> len(res)\n 1\n >>> new_index = res[0]\n >>> res = list(catalog.iterSearchIndexes())\n >>> len(res)\n 1\n >>> old_index = res[0]\n >>> new_index is old_index\n False\n >>> old_index.index is new_index.index\n False\n >>> list(old_index.index.keys()) == list(new_index.index.keys())\n True\n >>> from __future__ import print_function\n >>> for key, value in old_index.index.items():\n ... v = new_index.index[key]\n ... if v is value or list(v) != list(value):\n ... print('oops', key, value, v)\n ... break\n ... else:\n ... print('good')\n ...\n good\n >>> old_index.names is not new_index.names\n True\n >>> list(old_index.names) == list(new_index.names)\n True\n >>> for name, old_ix in old_index.names.items():\n ... new_ix = new_index.names[name]\n ... if new_ix is old_ix or list(new_ix.keys()) != list(old_ix.keys()):\n ... print('oops')\n ... break\n ... for key, value in old_ix.items():\n ... v = new_ix[key]\n ... if v is value or list(v) != list(value):\n ... print('oops', name, key, value, v)\n ... break\n ... else:\n ... continue\n ... break\n ... else:\n ... print('good')\n ...\n good\n\nHelpers\n=======\n\nWhen writing search indexes and query factories, you often want complete\naccess to relation catalog data. We've seen a number of these tools already:\n\n- `getRelationModuleTools` gets a dictionary of the BTree tools needed to\n work with relations.\n\n >>> sorted(catalog.getRelationModuleTools().keys())\n ... # doctest: +NORMALIZE_WHITESPACE\n ['BTree', 'Bucket', 'Set', 'TreeSet', 'difference', 'dump',\n 'intersection', 'load', 'multiunion', 'union']\n\n 'multiunion' is only there if the BTree is an I* or L* module.\n Use the zc.relation.catalog.multiunion helper function to do the\n best union you can for a given set of tools.\n\n- `getValueModuleTools` does the same for indexed values.\n\n >>> tools = set(('BTree', 'Bucket', 'Set', 'TreeSet', 'difference',\n ... 'dump', 'intersection', 'load', 'multiunion', 'union'))\n >>> tools.difference(catalog.getValueModuleTools('children').keys()) == set()\n True\n\n >>> tools.difference(catalog.getValueModuleTools('token').keys()) == set()\n True\n\n- `getRelationTokens` can return all of the tokens in the catalog.\n\n >>> len(catalog.getRelationTokens()) == len(catalog)\n True\n\n This also happens to be equivalent to `findRelationTokens` with an empty\n query.\n\n >>> catalog.getRelationTokens() is catalog.findRelationTokens({})\n True\n\n It also can return all the tokens that match a given query, or None if\n there are no matches.\n\n >>> catalog.getRelationTokens({'token': 0}) # doctest: +ELLIPSIS\n \n >>> list(catalog.getRelationTokens({'token': 0}))\n [100]\n\n This also happens to be equivalent to `findRelationTokens` with a query,\n a maxDepth of 1, and no other arguments.\n\n >>> catalog.findRelationTokens({'token': 0}, maxDepth=1) is (\n ... catalog.getRelationTokens({'token': 0}))\n True\n\n Except that if there are no matches, `findRelationTokens` returns an empty\n set (so it *always* returns an iterable).\n\n >>> catalog.findRelationTokens({'token': 50}, maxDepth=1)\n LOSet([])\n >>> print(catalog.getRelationTokens({'token': 50}))\n None\n\n- `getValueTokens` can return all of the tokens for a given value name in\n the catalog.\n\n >>> list(catalog.getValueTokens('token')) == list(range(12))\n True\n\n This is identical to catalog.findValueTokens with a name only (or with\n an empty query, and a maxDepth of 1).\n\n >>> list(catalog.findValueTokens('token')) == list(range(12))\n True\n >>> catalog.findValueTokens('token') is catalog.getValueTokens('token')\n True\n\n It can also return the values for a given token.\n\n >>> list(catalog.getValueTokens('children', 100))\n [1, 2]\n\n This is identical to catalog.findValueTokens with a name and a query of\n {None: token}.\n\n >>> list(catalog.findValueTokens('children', {None: 100}))\n [1, 2]\n >>> catalog.getValueTokens('children', 100) is (\n ... catalog.findValueTokens('children', {None: 100}))\n True\n\n Except that if there are no matches, `findValueTokens` returns an empty\n set (so it *always* returns an iterable); while getValueTokens will\n return None if the relation has no values (or the relation is unknown).\n\n >>> catalog.findValueTokens('children', {None: 50}, maxDepth=1)\n LFSet([])\n >>> print(catalog.getValueTokens('children', 50))\n None\n\n >>> rel.children.remove(27)\n >>> catalog.index(rel)\n >>> catalog.findValueTokens('children', {None: rel.id}, maxDepth=1)\n LFSet([])\n >>> print(catalog.getValueTokens('children', rel.id))\n None\n\n- `yieldRelationTokenChains` is a search workhorse for searches that use a\n query factory. TODO: describe.\n\n.. ......... ..\n.. Footnotes ..\n.. ......... ..\n\n.. [#queryFactory] The query factory knows when it is not needed--not only\n when neither of its names are used, but also when both of its names are\n used.\n\n >>> list(catalog.findRelationTokens({'token': 0, 'children': 1}))\n [100]\n\n.. [#findValuesUnindexed] When values are the same as their tokens,\n `findValues` returns the same result as `findValueTokens`. Here\n we see this without indexes.\n\n >>> list(catalog.findValueTokens('children', {'token': 0})) == list(\n ... catalog.findValues('children', {'token': 0}))\n True\n\n.. [#findValuesIndexed] Again, when values are the same as their tokens,\n `findValues` returns the same result as `findValueTokens`. Here\n we see this with indexes.\n\n >>> list(catalog.findValueTokens('children', {'token': 0})) == list(\n ... catalog.findValues('children', {'token': 0}))\n True\n\n\nOptimizing Relation Catalog Use\n===============================\n\nThere are several best practices and optimization opportunities in regards to\nthe catalog.\n\n- Use integer-keyed BTree sets when possible. They can use the BTrees'\n `multiunion` for a speed boost. Integers' __cmp__ is reliable, and in C.\n\n- Never use persistent objects as keys. They will cause a database load every\n time you need to look at them, they take up memory and object caches, and\n they (as of this writing) disable conflict resolution. Intids (or similar)\n are your best bet for representing objects, and some other immutable such as\n strings are the next-best bet, and zope.app.keyreferences (or similar) are\n after that.\n\n- Use multiple-token values in your queries when possible, especially in your\n transitive query factories.\n\n- Use the cache when you are loading and dumping tokens, and in your\n transitive query factories.\n\n- When possible, don't load or dump tokens (the values themselves may be used\n as tokens). This is especially important when you have multiple tokens:\n store them in a BTree structure in the same module as the zc.relation module\n for the value.\n\nFor some operations, particularly with hundreds or thousands of members in a\nsingle relation value, some of these optimizations can speed up some\ncommon-case reindexing work by around 100 times.\n\nThe easiest (and perhaps least useful) optimization is that all dump\ncalls and all load calls generated by a single operation share a cache\ndictionary per call type (dump/load), per indexed relation value.\nTherefore, for instance, we could stash an intids utility, so that we\nonly had to do a utility lookup once, and thereafter it was only a\nsingle dictionary lookup. This is what the default `generateToken` and\n`resolveToken` functions in zc.relationship's index.py do: look at them\nfor an example.\n\nA further optimization is to not load or dump tokens at all, but use values\nthat may be tokens. This will be particularly useful if the tokens have\n__cmp__ (or equivalent) in C, such as built-in types like ints. To specify\nthis behavior, you create an index with the 'load' and 'dump' values for the\nindexed attribute descriptions explicitly set to None.\n\n\n >>> import zope.interface\n >>> class IRelation(zope.interface.Interface):\n ... subjects = zope.interface.Attribute(\n ... 'The sources of the relation; the subject of the sentence')\n ... relationtype = zope.interface.Attribute(\n ... '''unicode: the single relation type of this relation;\n ... usually contains the verb of the sentence.''')\n ... objects = zope.interface.Attribute(\n ... '''the targets of the relation; usually a direct or\n ... indirect object in the sentence''')\n ...\n\n >>> import BTrees\n >>> relations = BTrees.family32.IO.BTree()\n >>> relations[99] = None # just to give us a start\n\n >>> @zope.interface.implementer(IRelation)\n ... class Relation(object):\n ...\n ... def __init__(self, subjects, relationtype, objects):\n ... self.subjects = subjects\n ... assert relationtype in relTypes\n ... self.relationtype = relationtype\n ... self.objects = objects\n ... self.id = relations.maxKey() + 1\n ... relations[self.id] = self\n ... def __repr__(self):\n ... return '<%r %s %r>' % (\n ... self.subjects, self.relationtype, self.objects)\n\n >>> def token(rel, self):\n ... return rel.token\n ...\n >>> def children(rel, self):\n ... return rel.children\n ...\n >>> def dumpRelation(obj, index, cache):\n ... return obj.id\n ...\n >>> def loadRelation(token, index, cache):\n ... return relations[token]\n ...\n\n >>> relTypes = ['has the role of']\n >>> def relTypeDump(obj, index, cache):\n ... assert obj in relTypes, 'unknown relationtype'\n ... return obj\n ...\n >>> def relTypeLoad(token, index, cache):\n ... assert token in relTypes, 'unknown relationtype'\n ... return token\n ...\n\n >>> import zc.relation.catalog\n >>> catalog = zc.relation.catalog.Catalog(\n ... dumpRelation, loadRelation)\n >>> catalog.addValueIndex(IRelation['subjects'], multiple=True)\n >>> catalog.addValueIndex(\n ... IRelation['relationtype'], relTypeDump, relTypeLoad,\n ... BTrees.family32.OI, name='reltype')\n >>> catalog.addValueIndex(IRelation['objects'], multiple=True)\n >>> import zc.relation.queryfactory\n >>> factory = zc.relation.queryfactory.TransposingTransitive(\n ... 'subjects', 'objects')\n >>> catalog.addDefaultQueryFactory(factory)\n\n >>> rel = Relation((1,), 'has the role of', (2,))\n >>> catalog.index(rel)\n >>> list(catalog.findValueTokens('objects', {'subjects': 1}))\n [2]\n\nIf you have single relations that relate hundreds or thousands of\nobjects, it can be a huge win if the value is a 'multiple' of the same\ntype as the stored BTree for the given attribute. The default BTree\nfamily for attributes is IFBTree; IOBTree is also a good choice, and may\nbe preferrable for some applications.\n\n >>> catalog.unindex(rel)\n >>> rel = Relation(\n ... BTrees.family32.IF.TreeSet((1,)), 'has the role of',\n ... BTrees.family32.IF.TreeSet())\n >>> catalog.index(rel)\n >>> list(catalog.findValueTokens('objects', {'subjects': 1}))\n []\n >>> list(catalog.findValueTokens('subjects', {'objects': None}))\n [1]\n\nReindexing is where some of the big improvements can happen. The following\ngyrations exercise the optimization code.\n\n >>> rel.objects.insert(2)\n 1\n >>> catalog.index(rel)\n >>> list(catalog.findValueTokens('objects', {'subjects': 1}))\n [2]\n >>> rel.subjects = BTrees.family32.IF.TreeSet((3,4,5))\n >>> catalog.index(rel)\n >>> list(catalog.findValueTokens('objects', {'subjects': 3}))\n [2]\n\n >>> rel.subjects.insert(6)\n 1\n >>> catalog.index(rel)\n >>> list(catalog.findValueTokens('objects', {'subjects': 6}))\n [2]\n\n >>> rel.subjects.update(range(100, 200))\n 100\n >>> catalog.index(rel)\n >>> list(catalog.findValueTokens('objects', {'subjects': 100}))\n [2]\n\n >>> rel.subjects = BTrees.family32.IF.TreeSet((3,4,5,6))\n >>> catalog.index(rel)\n >>> list(catalog.findValueTokens('objects', {'subjects': 3}))\n [2]\n\n >>> rel.subjects = BTrees.family32.IF.TreeSet(())\n >>> catalog.index(rel)\n >>> list(catalog.findValueTokens('objects', {'subjects': 3}))\n []\n\n >>> rel.subjects = BTrees.family32.IF.TreeSet((3,4,5))\n >>> catalog.index(rel)\n >>> list(catalog.findValueTokens('objects', {'subjects': 3}))\n [2]\n\ntokenizeValues and resolveValueTokens work correctly without loaders and\ndumpers--that is, they do nothing.\n\n >>> catalog.tokenizeValues((3,4,5), 'subjects')\n (3, 4, 5)\n >>> catalog.resolveValueTokens((3,4,5), 'subjects')\n (3, 4, 5)\n\n\n=======\nChanges\n=======\n\n\n1.1.post2 (2018-06-18)\n======================\n\n- Another attempt to fix PyPI page by using correct expected metadata syntax.\n\n\n1.1.post1 (2018-06-18)\n======================\n\n- Fix PyPI page by using correct ReST syntax.\n\n\n1.1 (2018-06-15)\n================\n\n- Add support for Python 3.5 and 3.6.\n\n\n1.0 (2008-04-23)\n================\n\nThis is the initial release of the zc.relation package. However, it\nrepresents a refactoring of another package, zc.relationship. This\npackage contains only a modified version of the relation(ship) index,\nnow called a catalog. The refactored version of zc.relationship index\nrelies on (subclasses) this catalog. zc.relationship also maintains a\nbackwards-compatible subclass.\n\nThis package only relies on the ZODB, zope.interface, and zope.testing\nsoftware, and can be used inside or outside of a standard ZODB database.\nThe software does have to be there, though (the package relies heavily\non the ZODB BTrees package).\n\nIf you would like to switch a legacy zc.relationship index to a\nzc.relation catalog, try this trick in your generations script.\nAssuming the old index is ``old``, the following line should create\na new zc.relation catalog with your legacy data:\n\n >>> new = old.copy(zc.relation.Catalog)\n\nWhy is the same basic data structure called a catalog now? Because we\nexposed the ability to mutate the data structure, and what you are really\nadding and removing are indexes. It didn't make sense to put an index in\nan index, but it does make sense to put an index in a catalog. Thus, a\nname change was born.\n\nThe catalog in this package has several incompatibilities from the earlier\nzc.relationship index, and many new features. The zc.relationship package\nmaintains a backwards-compatible subclass. The following discussion\ncompares the zc.relation catalog with the zc.relationship 1.x index.\n\nIncompatibilities with zc.relationship 1.x index\n------------------------------------------------\n\nThe two big changes are that method names now refer to ``Relation`` rather\nthan ``Relationship``; and the catalog is instantiated slightly differently\nfrom the index. A few other changes are worth your attention. The\nfollowing list attempts to highlight all incompatibilities.\n\n:Big incompatibilities:\n\n - ``findRelationshipTokenSet`` and ``findValueTokenSet`` are renamed, with\n some slightly different semantics, as ``getRelationTokens`` and\n ``getValueTokens``. The exact same result as\n ``findRelationTokenSet(query)`` can be obtained with\n ``findRelationTokens(query, 1)`` (where 1 is maxDepth). The same\n result as ``findValueTokenSet(reltoken, name)`` can be obtained with\n ``findValueTokens(name, {zc.relation.RELATION: reltoken}, 1)``.\n\n - ``findRelations`` replaces ``findRelatonships``. The new method will use\n the defaultTransitiveQueriesFactory if it is set and maxDepth is not 1.\n It shares the call signature of ``findRelationChains``.\n\n - ``isLinked`` is now ``canFind``.\n\n - The catalog instantiation arguments have changed from the old index.\n\n * ``load`` and ``dump`` (formerly ``loadRel`` and ``dumpRel``,\n respectively) are now required arguments for instantiation.\n\n * The only other optional arguments are ``btree`` (was ``relFamily``) and\n ``family``. You now specify what elements to index with\n ``addValueIndex``\n\n * Note also that ``addValueIndex`` defaults to no load and dump function,\n unlike the old instantiation options.\n\n - query factories are different. See ``IQueryFactory`` in the interfaces.\n\n * they first get (query, catalog, cache) and then return a getQueries\n callable that gets relchains and yields queries; OR None if they\n don't match.\n\n * They must also handle an empty relchain. Typically this should\n return the original query, but may also be used to mutate the\n original query.\n\n * They are no longer thought of as transitive query factories, but as\n general query mutators.\n\n:Medium:\n\n - The catalog no longer inherits from\n zope.app.container.contained.Contained.\n\n - The index requires ZODB 3.8 or higher.\n\n:Small:\n\n - ``deactivateSets`` is no longer an instantiation option (it was broken\n because of a ZODB bug anyway, as had been described in the\n documentation).\n\nChanges and new features\n------------------------\n\n- The catalog now offers the ability to index certain\n searches. The indexes must be explicitly instantiated and registered\n you want to optimize. This can be used when searching for values, when\n searching for relations, or when determining if two objects are\n linked. It cannot be used for relation chains. Requesting an index\n has the usual trade-offs of greater storage space and slower write\n speed for faster search speed. Registering a search index is done\n after instantiation time; you can iteratate over the current settings\n used, and remove them. (The code path expects to support legacy\n zc.relationship index instances for all of these APIs.)\n\n- You can now specify new values after the catalog has been created, iterate\n over the settings used, and remove values.\n\n- The catalog has a copy method, to quickly make new copies without actually\n having to reindex the relations.\n\n- query arguments can now specify multiple values for a given name by\n using zc.relation.catalog.any(1, 2, 3, 4) or\n zc.relation.catalog.Any((1, 2, 3, 4)).\n\n- The catalog supports specifying indexed values by passing callables rather\n than interface elements (which are also still supported).\n\n- ``findRelations`` and new method ``findRelationTokens`` can find\n relations transitively and intransitively. ``findRelationTokens``\n when used intransitively repeats the legacy zc.relationship index\n behavior of ``findRelationTokenSet``.\n (``findRelationTokenSet`` remains in the API, not deprecated, a companion\n to ``findValueTokenSet``.)\n\n- in findValues and findValueTokens, ``query`` argument is now optional. If\n the query evaluates to False in a boolean context, all values, or value\n tokens, are returned. Value tokens are explicitly returned using the\n underlying BTree storage. This can then be used directly for other BTree\n operations.\n\n- Completely new docs. Unfortunately, still really not good enough.\n\n- The package has drastically reduced direct dependecies from zc.relationship:\n it is now more clearly a ZODB tool, with no other Zope dependencies than\n zope.testing and zope.interface.\n\n- Listeners allow objects to listen to messages from the catalog (which can\n be used directly or, for instance, to fire off events).\n\n- You can search for relations, using a key of zc.relation.RELATION...which is\n really an alias for None. Sorry. But hey, use the constant! I think it is\n more readable.\n\n- tokenizeQuery (and resolveQuery) now accept keyword arguments as an\n alternative to a normal dict query. This can make constructing the query\n a bit more attractive (i.e., ``query = catalog.tokenizeQuery;\n res = catalog.findValues('object', query(subject=joe, predicate=OWNS))``).\n\n\n", "description_content_type": "", "docs_url": null, "download_url": "", "downloads": { "last_day": -1, "last_month": -1, "last_week": -1 }, "home_page": "https://github.com/zopefoundation/zc.relation", "keywords": "zope zope3 relation", "license": "ZPL 2.1", "maintainer": "", "maintainer_email": "", "name": "zc.relation", "package_url": "https://pypi.org/project/zc.relation/", "platform": "", "project_url": "https://pypi.org/project/zc.relation/", "project_urls": { "Homepage": "https://github.com/zopefoundation/zc.relation" }, "release_url": "https://pypi.org/project/zc.relation/1.1.post2/", "requires_dist": [ "ZODB3 (>=3.8dev)", "setuptools", "six", "zope.interface", "zope.testing", "zc.relationship (>=2.0c1); extra == 'test'" ], "requires_python": "", "summary": "Index intransitive and transitive n-ary relationships.", "version": "1.1.post2" }, "last_serial": 3972511, "releases": { "1.0": [ { "comment_text": "", "digests": { "md5": "7e479095954fc6d8f648951434695837", "sha256": "771ee928bce412f4eaeb6ebebb6dbf12ca2ba9dc4d60ad0a0dae0b608b57cdc5" }, "downloads": -1, "filename": "zc.relation-1.0.tar.gz", "has_sig": false, "md5_digest": "7e479095954fc6d8f648951434695837", "packagetype": "sdist", "python_version": "source", "requires_python": null, "size": 114754, "upload_time": "2008-04-24T01:12:56", "url": "https://files.pythonhosted.org/packages/bf/31/76b2c1e408136b3e61b5508d254b6ccc26c79b14dc440abe17aae05e3695/zc.relation-1.0.tar.gz" } ], "1.1": [ { "comment_text": "", "digests": { "md5": "f3b581153acda8fe4058e626deb1ae98", "sha256": "1d2de09eb5642fed4fd8df89391c2dcb378891fd64c0f1d7477eeb053d6e1757" }, "downloads": -1, "filename": "zc.relation-1.1.tar.gz", "has_sig": false, "md5_digest": "f3b581153acda8fe4058e626deb1ae98", "packagetype": "sdist", "python_version": "source", "requires_python": null, "size": 154289, "upload_time": "2018-06-15T06:38:19", "url": "https://files.pythonhosted.org/packages/ec/7e/956002bf9f288a32ec77c9133ccdbb35607e4605d4d137d97072668bbd67/zc.relation-1.1.tar.gz" } ], "1.1.post1": [ { "comment_text": "", "digests": { "md5": "52f4af8848f45693acf5c66ca9d73f80", "sha256": "77f9fb3d60c6728604042a10a266acdf97e9c1fbe831a5e0d8ba4384b6053bf7" }, "downloads": -1, "filename": "zc.relation-1.1.post1.tar.gz", "has_sig": false, "md5_digest": "52f4af8848f45693acf5c66ca9d73f80", "packagetype": "sdist", "python_version": "source", "requires_python": null, "size": 153856, "upload_time": "2018-06-18T05:55:03", "url": "https://files.pythonhosted.org/packages/a4/6c/fe9067c5e43d408f6d94e2b12d62999419e3f55509a03912481191f021c1/zc.relation-1.1.post1.tar.gz" } ], "1.1.post2": [ { "comment_text": "", "digests": { "md5": "15d3554fb077b5bc0d15ff9e732bf771", "sha256": "57218b4d18e1842eba33b96b53a13004fa2e187bc849887c3150be299e6fc261" }, "downloads": -1, "filename": "zc.relation-1.1.post2-py2.py3-none-any.whl", "has_sig": false, "md5_digest": "15d3554fb077b5bc0d15ff9e732bf771", "packagetype": "bdist_wheel", "python_version": "py2.py3", "requires_python": null, "size": 154716, "upload_time": "2018-06-18T06:05:31", "url": "https://files.pythonhosted.org/packages/10/ad/120f09e34e439f3340cc793d3a6f947ffdb06d88c38d2faf17a7b177d2f4/zc.relation-1.1.post2-py2.py3-none-any.whl" }, { "comment_text": "", "digests": { "md5": "deafd867bc219144118e96e3cffc64a4", "sha256": "b1aeb9e97ead0206a210e7f1fe32ae60f43630109e46e2ff40e99294fb892add" }, "downloads": -1, "filename": "zc.relation-1.1.post2.tar.gz", "has_sig": false, "md5_digest": "deafd867bc219144118e96e3cffc64a4", "packagetype": "sdist", "python_version": "source", "requires_python": null, "size": 153926, "upload_time": "2018-06-18T06:05:32", "url": "https://files.pythonhosted.org/packages/96/cd/0eab777ddfa4326d05bd24883ad469488345041b90fd849efa858e14184a/zc.relation-1.1.post2.tar.gz" } ] }, "urls": [ { "comment_text": "", "digests": { "md5": "15d3554fb077b5bc0d15ff9e732bf771", "sha256": "57218b4d18e1842eba33b96b53a13004fa2e187bc849887c3150be299e6fc261" }, "downloads": -1, "filename": "zc.relation-1.1.post2-py2.py3-none-any.whl", "has_sig": false, "md5_digest": "15d3554fb077b5bc0d15ff9e732bf771", "packagetype": "bdist_wheel", "python_version": "py2.py3", "requires_python": null, "size": 154716, "upload_time": "2018-06-18T06:05:31", "url": "https://files.pythonhosted.org/packages/10/ad/120f09e34e439f3340cc793d3a6f947ffdb06d88c38d2faf17a7b177d2f4/zc.relation-1.1.post2-py2.py3-none-any.whl" }, { "comment_text": "", "digests": { "md5": "deafd867bc219144118e96e3cffc64a4", "sha256": "b1aeb9e97ead0206a210e7f1fe32ae60f43630109e46e2ff40e99294fb892add" }, "downloads": -1, "filename": "zc.relation-1.1.post2.tar.gz", "has_sig": false, "md5_digest": "deafd867bc219144118e96e3cffc64a4", "packagetype": "sdist", "python_version": "source", "requires_python": null, "size": 153926, "upload_time": "2018-06-18T06:05:32", "url": "https://files.pythonhosted.org/packages/96/cd/0eab777ddfa4326d05bd24883ad469488345041b90fd849efa858e14184a/zc.relation-1.1.post2.tar.gz" } ] }