home *** CD-ROM | disk | FTP | other *** search
/ Clickx 115 / Clickx 115.iso / software / tools / windows / tails-i386-0.16.iso / live / filesystem.squashfs / usr / share / pyshared / rdflib / TextIndex.py < prev    next >
Encoding:
Python Source  |  2009-03-04  |  11.8 KB  |  309 lines

  1. try:
  2.     from hashlib import md5
  3. except ImportError:
  4.     from md5 import md5
  5.     
  6. from rdflib.BNode import BNode
  7. from rdflib.Graph import ConjunctiveGraph
  8. from rdflib.Literal import Literal
  9. from rdflib.Namespace import NamespaceDict as Namespace
  10. from rdflib.URIRef import URIRef
  11. from rdflib.store import TripleAddedEvent, TripleRemovedEvent
  12. from rdflib.store.IOMemory import IOMemory
  13. import logging
  14. import re #, stopdict
  15.  
  16. _logger = logging.getLogger(__name__)
  17.  
  18. def get_stopdict():
  19.     """Return a dictionary of stopwords."""
  20.     return _dict
  21.  
  22. _words = [
  23.     "a", "and", "are", "as", "at", "be", "but", "by",
  24.     "for", "if", "in", "into", "is", "it",
  25.     "no", "not", "of", "on", "or", "such",
  26.     "that", "the", "their", "then", "there", "these",
  27.     "they", "this", "to", "was", "will", "with"
  28. ]
  29.  
  30. _dict = {}
  31. for w in _words:
  32.     _dict[w] = None
  33.  
  34. word_pattern = re.compile(r"(?u)\w+")
  35. has_stop = get_stopdict().has_key
  36.  
  37. def splitter(s):
  38.     return word_pattern.findall(s)
  39.  
  40. def stopper(s):
  41.     return [w.lower() for w in s if not has_stop(w)]
  42.  
  43.  
  44.  
  45. class TextIndex(ConjunctiveGraph):
  46.     """
  47.     An rdflib graph event handler than indexes text literals that are
  48.     added to a another graph.
  49.  
  50.     This class lets you 'search' the text literals in an RDF graph.
  51.     Typically in RDF to search for a substring in an RDF graph you
  52.     would have to 'brute force' search every literal string looking
  53.     for your substring.
  54.  
  55.     Instead, this index stores the words in literals into another
  56.     graph whose structure makes searching for terms much less
  57.     expensive.  It does this by chopping up the literals into words,
  58.     removing very common words (currently only in English) and then
  59.     adding each of those words into an RDF graph that describes the
  60.     statements in the original graph that the word came from.
  61.  
  62.     First, let's create a graph that will transmit events and a text
  63.     index that will receive those events, and then subscribe the text
  64.     index to the event graph:
  65.  
  66.       >>> e = ConjunctiveGraph()
  67.       >>> t = TextIndex()
  68.       >>> t.subscribe_to(e)
  69.  
  70.     When triples are added to the event graph (e) events will be fired
  71.     that trigger event handlers in subscribers.  In this case our only
  72.     subscriber is a text index and its action is to index triples that
  73.     contain literal RDF objects.  Here are 3 such triples:
  74.  
  75.       >>> e.add((URIRef('a'), URIRef('title'), Literal('one two three')))
  76.       >>> e.add((URIRef('b'), URIRef('title'), Literal('two three four')))
  77.       >>> e.add((URIRef('c'), URIRef('title'), Literal('three four five')))
  78.  
  79.     Of the three literal objects that were added, they all contain
  80.     five unique terms.  These terms can be queried directly from the
  81.     text index:
  82.     
  83.       >>> t.term_strings() ==  set(['four', 'five', 'three', 'two', 'one'])
  84.       True
  85.  
  86.     Now we can search for statement that contain certain terms.  Let's
  87.     search for 'one' which occurs in only one of the literals
  88.     provided, 'a'.  This can be queried for:
  89.  
  90.       >>> t.search('one')
  91.       set([(rdflib.URIRef('a'), rdflib.URIRef('title'), None)])
  92.  
  93.     'one' and 'five' only occur in one statement each, 'two' and
  94.     'four' occur in two, and 'three' occurs in three statements:
  95.  
  96.       >>> len(list(t.search('one')))
  97.       1
  98.       >>> len(list(t.search('two')))
  99.       2
  100.       >>> len(list(t.search('three')))
  101.       3
  102.       >>> len(list(t.search('four')))
  103.       2
  104.       >>> len(list(t.search('five')))
  105.       1
  106.  
  107.     Lets add some more statements with different predicates.
  108.  
  109.       >>> e.add((URIRef('a'), URIRef('creator'), Literal('michel')))
  110.       >>> e.add((URIRef('b'), URIRef('creator'), Literal('Atilla the one Hun')))
  111.       >>> e.add((URIRef('c'), URIRef('creator'), Literal('michel')))
  112.       >>> e.add((URIRef('d'), URIRef('creator'), Literal('Hun Mung two')))
  113.  
  114.     Now 'one' occurs in two statements:
  115.  
  116.       >>> assert len(list(t.search('one'))) == 2
  117.  
  118.     And 'two' occurs in three statements, here they are:
  119.  
  120.       >>> t.search('two')
  121.       set([(rdflib.URIRef('d'), rdflib.URIRef('creator'), None), (rdflib.URIRef('a'), rdflib.URIRef('title'), None), (rdflib.URIRef('b'), rdflib.URIRef('title'), None)])
  122.  
  123.     The predicates that are searched can be restricted by provding an
  124.     argument to 'search()':
  125.  
  126.       >>> t.search('two', URIRef('creator'))
  127.       set([(rdflib.URIRef('d'), rdflib.URIRef('creator'), None)])
  128.  
  129.       >>> t.search('two', URIRef(u'title'))
  130.       set([(rdflib.URIRef('a'), rdflib.URIRef('title'), None), (rdflib.URIRef('b'), rdflib.URIRef('title'), None)])
  131.  
  132.     You can search for more than one term by simply including it in
  133.     the query:
  134.     
  135.       >>> t.search('two three', URIRef(u'title'))
  136.       set([(rdflib.URIRef('c'), rdflib.URIRef('title'), None), (rdflib.URIRef('a'), rdflib.URIRef('title'), None), (rdflib.URIRef('b'), rdflib.URIRef('title'), None)])
  137.  
  138.     The above query returns all the statements that contain 'two' OR
  139.     'three'.  For the documents that contain 'two' AND 'three', do an
  140.     intersection of two queries:
  141.  
  142.       >>> t.search('two', URIRef(u'title')).intersection(t.search(u'three', URIRef(u'title')))
  143.       set([(rdflib.URIRef('a'), rdflib.URIRef('title'), None), (rdflib.URIRef('b'), rdflib.URIRef('title'), None)])
  144.  
  145.     Intersection two queries like this is probably not the most
  146.     efficient way to do it, but for reasonable data sets this isn't a
  147.     problem.  Larger data sets will want to query the graph with
  148.     sparql or something else more efficient.
  149.  
  150.     In all the above queries, the object of each statement was always
  151.     'None'.  This is because the index graph does not store the object
  152.     data, that would make it very large, and besides the data is
  153.     available in the original data graph.  For convenience, a method
  154.     is provides to 'link' an index graph to a data graph.  This allows
  155.     the index to also provide object data in query results.
  156.  
  157.       >>> t.link_to(e)
  158.       >>> set([str(i[2]) for i in t.search('two', URIRef(u'title')).intersection(t.search(u'three', URIRef(u'title')))]) ==  set(['two three four', 'one two three'])
  159.       True
  160.  
  161.     You can remove the link by assigning None:
  162.  
  163.       >>> t.link_to(None)
  164.  
  165.     Unindexing means to remove statments from the index graph that
  166.     corespond to a statement in the data graph.  Note that while it is
  167.     possible to remove the index information of the occurances of
  168.     terms in statements, it is not possible to remove the terms
  169.     themselves, terms are 'absolute' and are never removed from the
  170.     index graph.  This is not a problem since languages have finite
  171.     terms:
  172.  
  173.       >>> e.remove((URIRef('a'), URIRef('creator'), Literal('michel')))
  174.       >>> e.remove((URIRef('b'), URIRef('creator'), Literal('Atilla the one Hun')))
  175.       >>> e.remove((URIRef('c'), URIRef('creator'), Literal('michel')))
  176.       >>> e.remove((URIRef('d'), URIRef('creator'), Literal('Hun Mung two')))
  177.  
  178.     Now 'one' only occurs in one statement:
  179.  
  180.       >>> assert len(list(t.search('one'))) == 1
  181.  
  182.     And 'two' only occurs in two statements, here they are:
  183.  
  184.       >>> t.search('two')
  185.       set([(rdflib.URIRef('a'), rdflib.URIRef('title'), None), (rdflib.URIRef('b'), rdflib.URIRef('title'), None)])
  186.  
  187.     The predicates that are searched can be restricted by provding an
  188.     argument to 'search()':
  189.  
  190.       >>> t.search('two', URIRef(u'creator'))
  191.       set([])
  192.  
  193.       >>> t.search('two', URIRef(u'title'))
  194.       set([(rdflib.URIRef('a'), rdflib.URIRef('title'), None), (rdflib.URIRef('b'), rdflib.URIRef('title'), None)])
  195.  
  196.     """
  197.  
  198.     linked_data = None
  199.  
  200.     text_index = Namespace('http://rdflib.net/text_index#')
  201.     term = Namespace('http://rdflib.net/text_index#')["term"]
  202.     termin = Namespace('http://rdflib.net/text_index#')["termin"]
  203.  
  204.     def __init__(self, store='default'):
  205.         super(TextIndex, self).__init__(store)
  206.  
  207.     def add_handler(self, event):
  208.         if type(event.triple[2]) is Literal:
  209.             self.index(event.triple)
  210.         
  211.     def remove_handler(self, event):
  212.         if type(event.triple[2]) is Literal:
  213.             self.unindex(event.triple)
  214.  
  215.     def index(self, (s, p, o)):
  216.         # this code is tricky so it's annotated.  unindex is the reverse of this method.
  217.                 
  218.         if type(o) is Literal:                            # first, only index statements that have a literal object
  219.             for word in stopper(splitter(o)):             # split the literal and remove any stopwords
  220.                 word = Literal(word)                      # create a new literal for each word in the object
  221.                 
  222.                 # if that word already exists in the statement
  223.                 # loop over each context the term occurs in
  224.                 if self.value(predicate=self.term, object=word, any=True): 
  225.                     for t in set(self.triples((None, self.term, word))):
  226.                         t = t[0]
  227.                         # if the graph does not contain an occurance of the term in the statement's subject
  228.                         # then add it
  229.                         if not (t, self.termin, s) in self:
  230.                             self.add((t, self.termin, s))
  231.  
  232.                         # ditto for the predicate
  233.                         if not (p, t, s) in self:
  234.                             self.add((p, t, s))
  235.  
  236.                 else: # if the term does not exist in the graph, add it, and the references to the statement.
  237.                     # t gets used as a predicate, create identifier accordingly (AKA can't be a BNode)
  238.                     h = md5(word.encode('utf-8')); h.update(s.encode('utf-8')); h.update(p.encode('utf-8'))
  239.                     t = self.text_index["term_%s" % h.hexdigest()]
  240.                     self.add((t, self.term, word))
  241.                     self.add((t, self.termin, s))
  242.                     self.add((p, t, s))
  243.         
  244.     def unindex(self, (s, p, o)):
  245.         if type(o) is Literal:
  246.             for word in stopper(splitter(o)):
  247.                 word = Literal(word)
  248.                 if self.value(predicate=self.term, object=word, any=True):
  249.                     for t in self.triples((None, self.term, word)):
  250.                         t = t[0]
  251.                         if (t, self.termin, s) in self:
  252.                             self.remove((t, self.termin, s))
  253.                         if (p, t, s) in self:
  254.                             self.remove((p, t, s))
  255.  
  256.     def terms(self):
  257.         """ Returns a generator that yields all of the term literals in the graph. """
  258.         return set(self.objects(None, self.term))
  259.  
  260.     def term_strings(self):
  261.         """ Return a list of term strings. """
  262.         return set([str(i) for i in self.terms()])
  263.  
  264.     def search(self, terms, predicate=None):
  265.         """ Returns a set of all the statements the term occurs in. """
  266.         if predicate and not isinstance(predicate, URIRef):
  267.             _logger.warning("predicate is not a URIRef")
  268.             predicate = URIRef(predicate)
  269.         results = set()
  270.         terms = [Literal(term) for term in stopper(splitter(terms))]    
  271.  
  272.         for term in terms:
  273.             for t in self.triples((None, self.term, term)):
  274.                 for o in self.objects(t[0], self.termin):
  275.                     for p in self.triples((predicate, t[0], o)):
  276.                         if self.linked_data is None:
  277.                             results.add((o, p[0], None))
  278.                         else:
  279.                             results.add((o, p[0], self.linked_data.value(o, p[0])))
  280.         return results
  281.  
  282.     def index_graph(self, graph):
  283.         """
  284.         Index a whole graph.  Must be a conjunctive graph.
  285.         """
  286.         for t in graph.triples((None,None,None)):
  287.             self.index(t)
  288.  
  289.     def link_to(self, graph):
  290.         """
  291.         Link to a graph
  292.         """
  293.         self.linked_data = graph
  294.  
  295.     def subscribe_to(self, graph):
  296.         """
  297.         Subscribe this index to a graph.
  298.         """
  299.         graph.store.dispatcher.subscribe(TripleAddedEvent, self.add_handler)
  300.         graph.store.dispatcher.subscribe(TripleRemovedEvent, self.remove_handler)
  301.  
  302.  
  303. def test():
  304.     import doctest
  305.     doctest.testmod()
  306.  
  307. if __name__ == '__main__':
  308.     test()
  309.