|
| 1 | +from elasticsearch_dsl import Document, Percolator, Text, Keyword, \ |
| 2 | + connections, Q, Search |
| 3 | + |
| 4 | +connections.create_connection() |
| 5 | + |
| 6 | +class BlogPost(Document): |
| 7 | + """ |
| 8 | + Blog posts that will be automatically tagged based on percolation queries. |
| 9 | + """ |
| 10 | + content = Text() |
| 11 | + tags = Keyword(multi=True) |
| 12 | + |
| 13 | + class Index: |
| 14 | + name = 'test-blogpost' |
| 15 | + |
| 16 | + def add_tags(self): |
| 17 | + # run a percolation to automatically tag the blog post. |
| 18 | + s = Search(index='test-percolator') |
| 19 | + s = s.query('percolate', |
| 20 | + field='query', |
| 21 | + index=self._get_index(), |
| 22 | + document=self.to_dict()) |
| 23 | + |
| 24 | + # collect all the tags from matched percolators |
| 25 | + for percolator in s: |
| 26 | + self.tags.extend(percolator.tags) |
| 27 | + |
| 28 | + # make sure tags are unique |
| 29 | + self.tags = list(set(self.tags)) |
| 30 | + |
| 31 | + def save(self, **kwargs): |
| 32 | + self.add_tags() |
| 33 | + return super(BlogPost, self).save(**kwargs) |
| 34 | + |
| 35 | +class PercolatorDoc(Document): |
| 36 | + """ |
| 37 | + Document class used for storing the percolation queries. |
| 38 | + """ |
| 39 | + # relevant fields from BlogPost must be also present here for the queries |
| 40 | + # to be able to use them. Another option would be to use document |
| 41 | + # inheritance but save() would have to be reset to normal behavior. |
| 42 | + content = Text() |
| 43 | + |
| 44 | + # the percolator query to be run against the doc |
| 45 | + query = Percolator() |
| 46 | + # list of tags to append to a document |
| 47 | + tags = Keyword(multi=True) |
| 48 | + |
| 49 | + class Index: |
| 50 | + name = 'test-percolator' |
| 51 | + |
| 52 | +def setup(): |
| 53 | + # create the percolator index if it doesn't exist |
| 54 | + if not PercolatorDoc._index.exists(): |
| 55 | + PercolatorDoc.init() |
| 56 | + |
| 57 | + # register a percolation query looking for documents about python |
| 58 | + PercolatorDoc( |
| 59 | + _id='python', |
| 60 | + tags=['programming', 'development', 'python'], |
| 61 | + query=Q('match', content='python') |
| 62 | + ).save(refresh=True) |
0 commit comments