From ed4ef56225308b0408e49a12dc321403255bb87c Mon Sep 17 00:00:00 2001 From: David Sauve Date: Wed, 21 Oct 2009 08:41:27 -0400 Subject: [PATCH 01/98] Started work in refactor --- tests/xapian_tests/tests/__init__.py | 2 +- tests/xapian_tests/tests/xapian_query.py | 145 ++++++++++++----------- xapian_backend.py | 112 ++++------------- 3 files changed, 96 insertions(+), 163 deletions(-) diff --git a/tests/xapian_tests/tests/__init__.py b/tests/xapian_tests/tests/__init__.py index 25b3a6f..5b721c7 100644 --- a/tests/xapian_tests/tests/__init__.py +++ b/tests/xapian_tests/tests/__init__.py @@ -18,4 +18,4 @@ import warnings warnings.simplefilter('ignore', Warning) from xapian_tests.tests.xapian_query import * -from xapian_tests.tests.xapian_backend import * +# from xapian_tests.tests.xapian_backend import * diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index cc1fdc5..b3568cd 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -21,6 +21,7 @@ from django.conf import settings from django.test import TestCase from haystack.backends.xapian_backend import SearchBackend, SearchQuery +from haystack.query import SQ from core.models import MockModel, AnotherMockModel @@ -49,78 +50,78 @@ class XapianSearchQueryTestCase(TestCase): super(XapianSearchQueryTestCase, self).tearDown() def test_build_query_all(self): - self.assertEqual(self.sq.build_query(), '*') - + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query()') + def test_build_query_single_word(self): - self.sq.add_filter('content', 'hello') - self.assertEqual(self.sq.build_query(), 'hello') - + self.sq.add_filter(SQ(content='hello')) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(hello)') + def test_build_query_multiple_words_and(self): - self.sq.add_filter('content', 'hello') - self.sq.add_filter('content', 'world') - self.assertEqual(self.sq.build_query(), 'hello AND world') - + self.sq.add_filter(SQ(content='hello')) + self.sq.add_filter(SQ(content='world')) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND world))') + def test_build_query_multiple_words_not(self): - self.sq.add_filter('content', 'hello', use_not=True) - self.sq.add_filter('content', 'world', use_not=True) - self.assertEqual(self.sq.build_query(), 'NOT hello NOT world') - - def test_build_query_multiple_words_or(self): - self.sq.add_filter('content', 'hello', use_or=True) - self.sq.add_filter('content', 'world', use_or=True) - self.assertEqual(self.sq.build_query(), 'hello OR world') - - def test_build_query_multiple_words_mixed(self): - self.sq.add_filter('content', 'why') - self.sq.add_filter('content', 'hello', use_or=True) - self.sq.add_filter('content', 'world', use_not=True) - self.assertEqual(self.sq.build_query(), 'why OR hello NOT world') - - def test_build_query_phrase(self): - self.sq.add_filter('content', 'hello world') - self.assertEqual(self.sq.build_query(), '"hello world"') - - def test_build_query_multiple_filter_types(self): - self.sq.add_filter('content', 'why') - self.sq.add_filter('pub_date__lte', datetime.datetime(2009, 2, 10, 1, 59)) - self.sq.add_filter('author__gt', 'david') - self.sq.add_filter('created__lt', datetime.datetime(2009, 2, 12, 12, 13)) - self.sq.add_filter('title__gte', 'B') - self.sq.add_filter('id__in', [1, 2, 3]) - self.assertEqual(self.sq.build_query(), 'why AND pub_date:..20090210015900 AND NOT author:..david AND NOT created:20090212121300..* AND title:B..* AND (id:1 OR id:2 OR id:3)') - - def test_build_query_multiple_exclude_types(self): - self.sq.add_filter('content', 'why', use_not=True) - self.sq.add_filter('pub_date__lte', datetime.datetime(2009, 2, 10, 1, 59), use_not=True) - self.sq.add_filter('author__gt', 'david', use_not=True) - self.sq.add_filter('created__lt', datetime.datetime(2009, 2, 12, 12, 13), use_not=True) - self.sq.add_filter('title__gte', 'B', use_not=True) - self.sq.add_filter('id__in', [1, 2, 3], use_not=True) - self.assertEqual(self.sq.build_query(), 'NOT why AND NOT pub_date:..20090210015900 AND author:..david AND created:20090212121300..* AND NOT title:B..* AND NOT id:1 NOT id:2 NOT id:3') - - def test_build_query_wildcard_filter_types(self): - self.sq.add_filter('content', 'why') - self.sq.add_filter('title__startswith', 'haystack') - self.assertEqual(self.sq.build_query(), 'why AND title:haystack*') - - def test_clean(self): - self.assertEqual(self.sq.clean('hello world'), 'hello world') - self.assertEqual(self.sq.clean('hello AND world'), 'hello and world') - self.assertEqual(self.sq.clean('hello AND OR NOT + - && || ! ( ) { } [ ] ^ " ~ * ? : \ world'), 'hello and or not \\+ \\- \\&& \\|| \\! \\( \\) \\{ \\} \\[ \\] \\^ \\" \\~ \\* \\? \\: \\\\ world') - self.assertEqual(self.sq.clean('so please NOTe i am in a bAND and bORed'), 'so please NOTe i am in a bAND and bORed') - - def test_build_query_with_models(self): - self.sq.add_filter('content', 'hello') - self.sq.add_model(MockModel) - self.assertEqual(self.sq.build_query(), u'(hello) django_ct:core.mockmodel') - - self.sq.add_model(AnotherMockModel) - self.assertEqual(self.sq.build_query(), u'(hello) django_ct:core.anothermockmodel django_ct:core.mockmodel') - - def test_build_query_with_datetime(self): - self.sq.add_filter('pub_date', datetime.datetime(2009, 5, 9, 16, 20)) - self.assertEqual(self.sq.build_query(), u'pub_date:20090509162000') - - def test_build_query_with_sequence_and_filter_not_in(self): - self.sq.add_filter('id__exact', [1, 2, 3]) - self.assertEqual(self.sq.build_query(), u'id:[1, 2, 3]') \ No newline at end of file + self.sq.add_filter(~SQ(content='hello')) + self.sq.add_filter(~SQ(content='world')) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((NOT hello NOT world))') + + # def test_build_query_multiple_words_or(self): + # self.sq.add_filter('content', 'hello', use_or=True) + # self.sq.add_filter('content', 'world', use_or=True) + # self.assertEqual(self.sq.build_query(), 'hello OR world') + # + # def test_build_query_multiple_words_mixed(self): + # self.sq.add_filter('content', 'why') + # self.sq.add_filter('content', 'hello', use_or=True) + # self.sq.add_filter('content', 'world', use_not=True) + # self.assertEqual(self.sq.build_query(), 'why OR hello NOT world') + # + # def test_build_query_phrase(self): + # self.sq.add_filter('content', 'hello world') + # self.assertEqual(self.sq.build_query(), '"hello world"') + # + # def test_build_query_multiple_filter_types(self): + # self.sq.add_filter('content', 'why') + # self.sq.add_filter('pub_date__lte', datetime.datetime(2009, 2, 10, 1, 59)) + # self.sq.add_filter('author__gt', 'david') + # self.sq.add_filter('created__lt', datetime.datetime(2009, 2, 12, 12, 13)) + # self.sq.add_filter('title__gte', 'B') + # self.sq.add_filter('id__in', [1, 2, 3]) + # self.assertEqual(self.sq.build_query(), 'why AND pub_date:..20090210015900 AND NOT author:..david AND NOT created:20090212121300..* AND title:B..* AND (id:1 OR id:2 OR id:3)') + # + # def test_build_query_multiple_exclude_types(self): + # self.sq.add_filter('content', 'why', use_not=True) + # self.sq.add_filter('pub_date__lte', datetime.datetime(2009, 2, 10, 1, 59), use_not=True) + # self.sq.add_filter('author__gt', 'david', use_not=True) + # self.sq.add_filter('created__lt', datetime.datetime(2009, 2, 12, 12, 13), use_not=True) + # self.sq.add_filter('title__gte', 'B', use_not=True) + # self.sq.add_filter('id__in', [1, 2, 3], use_not=True) + # self.assertEqual(self.sq.build_query(), 'NOT why AND NOT pub_date:..20090210015900 AND author:..david AND created:20090212121300..* AND NOT title:B..* AND NOT id:1 NOT id:2 NOT id:3') + # + # def test_build_query_wildcard_filter_types(self): + # self.sq.add_filter('content', 'why') + # self.sq.add_filter('title__startswith', 'haystack') + # self.assertEqual(self.sq.build_query(), 'why AND title:haystack*') + # + # def test_clean(self): + # self.assertEqual(self.sq.clean('hello world'), 'hello world') + # self.assertEqual(self.sq.clean('hello AND world'), 'hello and world') + # self.assertEqual(self.sq.clean('hello AND OR NOT + - && || ! ( ) { } [ ] ^ " ~ * ? : \ world'), 'hello and or not \\+ \\- \\&& \\|| \\! \\( \\) \\{ \\} \\[ \\] \\^ \\" \\~ \\* \\? \\: \\\\ world') + # self.assertEqual(self.sq.clean('so please NOTe i am in a bAND and bORed'), 'so please NOTe i am in a bAND and bORed') + # + # def test_build_query_with_models(self): + # self.sq.add_filter('content', 'hello') + # self.sq.add_model(MockModel) + # self.assertEqual(self.sq.build_query(), u'(hello) django_ct:core.mockmodel') + # + # self.sq.add_model(AnotherMockModel) + # self.assertEqual(self.sq.build_query(), u'(hello) django_ct:core.anothermockmodel django_ct:core.mockmodel') + # + # def test_build_query_with_datetime(self): + # self.sq.add_filter('pub_date', datetime.datetime(2009, 5, 9, 16, 20)) + # self.assertEqual(self.sq.build_query(), u'pub_date:20090509162000') + # + # def test_build_query_with_sequence_and_filter_not_in(self): + # self.sq.add_filter('id__exact', [1, 2, 3]) + # self.assertEqual(self.sq.build_query(), u'id:[1, 2, 3]') \ No newline at end of file diff --git a/xapian_backend.py b/xapian_backend.py index ab4f4ad..d18f048 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -919,10 +919,9 @@ class SearchBackend(BaseSearchBackend): class SearchQuery(BaseSearchQuery): """ - `SearchQuery` is responsible for converting search queries into a format - that Xapian can understand. - - Most of the work is done by the :method:`build_query`. + This class is the Xapian specific version of the SearchQuery class. + It acts as an intermediary between the ``SearchQuerySet`` and the + ``SearchBackend`` itself. """ def __init__(self, backend=None): """ @@ -930,103 +929,33 @@ class SearchQuery(BaseSearchQuery): specified. If no backend is set, will use the Xapian `SearchBackend`. Optional arguments: - `backend` -- The `SearchBackend` to use (default = None) + ``backend`` -- The ``SearchBackend`` to use (default = None) """ super(SearchQuery, self).__init__(backend=backend) self.backend = backend or SearchBackend() def build_query(self): - """ - Builds a search query from previously set values, returning a query - string in a format ready for use by the Xapian `SearchBackend`. + if not self.query_filter: + return xapian.Query('') + + values = [] - Returns: - A query string suitable for parsing by Xapian. - """ - query = '' - - if not self.query_filters: - query = '*' - else: - query_chunks = [] - - for the_filter in self.query_filters: - if the_filter.is_and(): - query_chunks.append('AND') - - if the_filter.is_or(): - query_chunks.append('OR') - - if the_filter.is_not() and the_filter.field == 'content': - query_chunks.append('NOT') - - value = the_filter.value + for child in self.query_filter.children: + if isinstance(child, self.query_filter.__class__): + print 'SQ: ', child # TODO: Recursive call down tree... + else: + expression, value = child + field, filter_type = self.query_filter.split_expression(expression) + values.append(value) - if not isinstance(value, (list, tuple)): - # Convert whatever we find to what xapian wants. - value = self.backend._marshal_value(value) - - # Check to see if it's a phrase for an exact match. - if ' ' in value: - value = '"%s"' % value - - # 'content' is a special reserved word, much like 'pk' in - # Django's ORM layer. It indicates 'no special field'. - if the_filter.field == 'content': - query_chunks.append(value) - else: - if the_filter.is_not(): - query_chunks.append('AND') - filter_types = { - 'exact': 'NOT %s:%s', - 'gte': 'NOT %s:%s..*', - 'gt': '%s:..%s', - 'lte': 'NOT %s:..%s', - 'lt': '%s:%s..*', - 'startswith': 'NOT %s:%s*', - } - else: - filter_types = { - 'exact': '%s:%s', - 'gte': '%s:%s..*', - 'gt': 'NOT %s:..%s', - 'lte': '%s:..%s', - 'lt': 'NOT %s:%s..*', - 'startswith': '%s:%s*', - } - - if the_filter.filter_type != 'in': - query_chunks.append(filter_types[the_filter.filter_type] % (the_filter.field, value)) - else: - in_options = [] - if the_filter.is_not(): - for possible_value in value: - in_options.append('%s:%s' % (the_filter.field, possible_value)) - query_chunks.append('NOT %s' % ' NOT '.join(in_options)) - else: - for possible_value in value: - in_options.append('%s:%s' % (the_filter.field, possible_value)) - query_chunks.append('(%s)' % ' OR '.join(in_options)) - - if query_chunks[0] in ('AND', 'OR'): - # Pull off an undesirable leading "AND" or "OR". - del(query_chunks[0]) - - query = ' '.join(query_chunks) - - if len(self.models): - models = ['django_ct:%s.%s' % (model._meta.app_label, model._meta.module_name) for model in self.models] - models_clause = ' '.join(models) - final_query = '(%s) %s' % (query, models_clause) - - else: - final_query = query - - return final_query + return xapian.Query(xapian.Query.OP_AND, values) def run(self, spelling_query=None): """ Builds and executes the query. Returns a list of search results. + + Returns: + List of search results """ final_query = self.build_query() kwargs = { @@ -1069,6 +998,9 @@ class SearchQuery(BaseSearchQuery): def run_mlt(self): """ Builds and executes the query. Returns a list of search results. + + Returns: + List of search results """ if self._more_like_this is False or self._mlt_instance is None: raise MoreLikeThisError("No instance was provided to determine 'More Like This' results.") From 0a63686593aa8a6a68262ee306d0025ed9296340 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Wed, 21 Oct 2009 16:20:17 -0400 Subject: [PATCH 02/98] More changes to build_query --- xapian_backend.py | 50 +++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 44 insertions(+), 6 deletions(-) diff --git a/xapian_backend.py b/xapian_backend.py index d18f048..12774d4 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -935,11 +935,9 @@ class SearchQuery(BaseSearchQuery): self.backend = backend or SearchBackend() def build_query(self): - if not self.query_filter: - return xapian.Query('') - values = [] - + + return final_query for child in self.query_filter.children: if isinstance(child, self.query_filter.__class__): print 'SQ: ', child # TODO: Recursive call down tree... @@ -947,9 +945,49 @@ class SearchQuery(BaseSearchQuery): expression, value = child field, filter_type = self.query_filter.split_expression(expression) values.append(value) - + return xapian.Query(xapian.Query.OP_AND, values) - + + def build_query_fragment(self, field, filter_type, value): + """ + Builds a search query fragment from a field, filter type and value. + Returns: + A query string fragment suitable for parsing by Xapian. + """ + result = '' + + if not isinstance(value, (list, tuple)): + # Convert whatever we find to what xapian wants. + value = self.backend._marshal_value(value) + + # Check to see if it's a phrase for an exact match. + if ' ' in value: + value = '"%s"' % value + + # 'content' is a special reserved word, much like 'pk' in + # Django's ORM layer. It indicates 'no special field'. + if field == 'content': + result = value + else: + filter_types = { + 'exact': '%s:%s', + 'gte': '%s:%s..*', + 'gt': 'NOT %s:..%s', + 'lte': '%s:..%s', + 'lt': 'NOT %s:%s..*', + 'startswith': '%s:%s*', + } + + if filter_type != 'in': + result = filter_types[filter_type] % (field, value) + else: + in_options = [] + for possible_value in value: + in_options.append('%s:%s' % (field, possible_value)) + result = '(%s)' % ' OR '.join(in_options) + + return result + def run(self, spelling_query=None): """ Builds and executes the query. Returns a list of search results. From 7da4ea8fd19794102409664f75b9b13018ba18fb Mon Sep 17 00:00:00 2001 From: David Sauve Date: Tue, 27 Oct 2009 22:03:04 -0400 Subject: [PATCH 03/98] Work on refactoring. Eliminated a lot of useless code and started to implement build_query using xapian.Query --- xapian_backend.py | 175 +++++++++++++++------------------------------- 1 file changed, 57 insertions(+), 118 deletions(-) diff --git a/xapian_backend.py b/xapian_backend.py index 12774d4..5534591 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -933,125 +933,64 @@ class SearchQuery(BaseSearchQuery): """ super(SearchQuery, self).__init__(backend=backend) self.backend = backend or SearchBackend() - + def build_query(self): - values = [] - - return final_query - for child in self.query_filter.children: - if isinstance(child, self.query_filter.__class__): - print 'SQ: ', child # TODO: Recursive call down tree... - else: - expression, value = child - field, filter_type = self.query_filter.split_expression(expression) - values.append(value) - - return xapian.Query(xapian.Query.OP_AND, values) - - def build_query_fragment(self, field, filter_type, value): - """ - Builds a search query fragment from a field, filter type and value. - Returns: - A query string fragment suitable for parsing by Xapian. - """ - result = '' - - if not isinstance(value, (list, tuple)): - # Convert whatever we find to what xapian wants. - value = self.backend._marshal_value(value) - - # Check to see if it's a phrase for an exact match. - if ' ' in value: - value = '"%s"' % value - - # 'content' is a special reserved word, much like 'pk' in - # Django's ORM layer. It indicates 'no special field'. - if field == 'content': - result = value + if not self.query_filter.children: + return xapian.Query('') else: - filter_types = { - 'exact': '%s:%s', - 'gte': '%s:%s..*', - 'gt': 'NOT %s:..%s', - 'lte': '%s:..%s', - 'lt': 'NOT %s:%s..*', - 'startswith': '%s:%s*', - } + query_list = [] + + for child in self.query_filter.children: + if isinstance(child, self.query_filter.__class__): + pass + else: + expression, value = child + field, filter_type = self.query_filter.split_expression(expression) + query_list.append(xapian.Query(value)) + + return xapian.Query(xapian.Query.OP_AND, query_list) + - if filter_type != 'in': - result = filter_types[filter_type] % (field, value) - else: - in_options = [] - for possible_value in value: - in_options.append('%s:%s' % (field, possible_value)) - result = '(%s)' % ' OR '.join(in_options) - - return result - - def run(self, spelling_query=None): - """ - Builds and executes the query. Returns a list of search results. - - Returns: - List of search results - """ - final_query = self.build_query() - kwargs = { - 'start_offset': self.start_offset, - } - - if self.order_by: - kwargs['sort_by'] = self.order_by - - if self.end_offset is not None: - kwargs['end_offset'] = self.end_offset - self.start_offset - - if self.highlight: - kwargs['highlight'] = self.highlight - - if self.facets: - kwargs['facets'] = list(self.facets) - - if self.date_facets: - kwargs['date_facets'] = self.date_facets - - if self.query_facets: - kwargs['query_facets'] = self.query_facets - - if self.narrow_queries: - kwargs['narrow_queries'] = self.narrow_queries - - if spelling_query: - kwargs['spelling_query'] = spelling_query - - if self.boost: - kwargs['boost'] = self.boost - - results = self.backend.search(final_query, **kwargs) - self._results = results.get('results', []) - self._hit_count = results.get('hits', 0) - self._facet_counts = results.get('facets', {}) - self._spelling_suggestion = results.get('spelling_suggestion', None) + # def build_query_fragment(self, field, filter_type, value): + # print 'field: ', field + # print 'filter_type: ', filter_type + # print 'value: ', value - def run_mlt(self): - """ - Builds and executes the query. Returns a list of search results. - - Returns: - List of search results - """ - if self._more_like_this is False or self._mlt_instance is None: - raise MoreLikeThisError("No instance was provided to determine 'More Like This' results.") - - additional_query_string = self.build_query() - kwargs = { - 'start_offset': self.start_offset, - } - - if self.end_offset is not None: - kwargs['end_offset'] = self.end_offset - self.start_offset - - results = self.backend.more_like_this(self._mlt_instance, additional_query_string, **kwargs) - self._results = results.get('results', []) - self._hit_count = results.get('hits', 0) - + # """ + # Builds a search query fragment from a field, filter type and value. + # Returns: + # A query string fragment suitable for parsing by Xapian. + # """ + # result = '' + # + # if not isinstance(value, (list, tuple)): + # # Convert whatever we find to what xapian wants. + # value = self.backend._marshal_value(value) + # + # # Check to see if it's a phrase for an exact match. + # if ' ' in value: + # value = '"%s"' % value + # + # # 'content' is a special reserved word, much like 'pk' in + # # Django's ORM layer. It indicates 'no special field'. + # if field == 'content': + # result = value + # else: + # filter_types = { + # 'exact': '%s:%s', + # 'gte': '%s:%s..*', + # 'gt': 'NOT %s:..%s', + # 'lte': '%s:..%s', + # 'lt': 'NOT %s:%s..*', + # 'startswith': '%s:%s*', + # } + # + # if filter_type != 'in': + # result = filter_types[filter_type] % (field, value) + # else: + # in_options = [] + # for possible_value in value: + # in_options.append('%s:%s' % (field, possible_value)) + # result = '(%s)' % ' OR '.join(in_options) + # + # return result From 29ae7c58854f2284476a8b736c9b7b3705af8dba Mon Sep 17 00:00:00 2001 From: David Sauve Date: Mon, 9 Nov 2009 20:01:20 -0500 Subject: [PATCH 04/98] More refactor work --- tests/xapian_tests/tests/xapian_query.py | 22 +++++------ xapian_backend.py | 48 ++++++++++++++++-------- 2 files changed, 44 insertions(+), 26 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index b3568cd..4ec3ee5 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -49,22 +49,22 @@ class XapianSearchQueryTestCase(TestCase): settings.HAYSTACK_XAPIAN_PATH = self.old_xapian_path super(XapianSearchQueryTestCase, self).tearDown() - def test_build_query_all(self): - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query()') + # def test_build_query_all(self): + # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query()') def test_build_query_single_word(self): self.sq.add_filter(SQ(content='hello')) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(hello)') - def test_build_query_multiple_words_and(self): - self.sq.add_filter(SQ(content='hello')) - self.sq.add_filter(SQ(content='world')) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND world))') - - def test_build_query_multiple_words_not(self): - self.sq.add_filter(~SQ(content='hello')) - self.sq.add_filter(~SQ(content='world')) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((NOT hello NOT world))') + # def test_build_query_multiple_words_and(self): + # self.sq.add_filter(SQ(content='hello')) + # self.sq.add_filter(SQ(content='world')) + # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND world))') + # + # def test_build_query_multiple_words_not(self): + # self.sq.add_filter(~SQ(content='hello')) + # self.sq.add_filter(~SQ(content='world')) + # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((NOT hello NOT world))') # def test_build_query_multiple_words_or(self): # self.sq.add_filter('content', 'hello', use_or=True) diff --git a/xapian_backend.py b/xapian_backend.py index 5534591..16725f6 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -933,24 +933,42 @@ class SearchQuery(BaseSearchQuery): """ super(SearchQuery, self).__init__(backend=backend) self.backend = backend or SearchBackend() + + def as_xapian_query(self, parent, query_fragment_callback): + query_list = [] + + for child in parent.children: + if hasattr(child, 'as_query_string'): + query_list.append(self.as_xapian_query(child, query_fragment_callback)) + else: + expression, value = child + field, filter_type = self.query_filter.split_expression(expression) + query_list.append(query_fragment_callback(field, filter_type, value)) + + return xapian.Query(xapian.Query.OP_AND, query_list) def build_query(self): - if not self.query_filter.children: - return xapian.Query('') - else: - query_list = [] - - for child in self.query_filter.children: - if isinstance(child, self.query_filter.__class__): - pass - else: - expression, value = child - field, filter_type = self.query_filter.split_expression(expression) - query_list.append(xapian.Query(value)) - - return xapian.Query(xapian.Query.OP_AND, query_list) - + query = self.as_xapian_query(self.query_filter, self.build_query_fragment) + def build_query_fragment(self, field, filter_type, value): + return xapian.Query(value) + + # + # if not self.query_filter.children: + # return xapian.Query('') + # else: + # query_list = [] + # + # for child in self.query_filter.children: + # if isinstance(child, self.query_filter.__class__): + # query_list.append(self.build_query(child)) + # else: + # expression, value = child + # field, filter_type = self.query_filter.split_expression(expression) + # query_list.append(xapian.Query(value)) + # + # return xapian.Query(xapian.Query.OP_AND, query_list) + # def build_query_fragment(self, field, filter_type, value): # print 'field: ', field # print 'filter_type: ', filter_type From c06277188781c52ffa95de1b377b0f248d8056ef Mon Sep 17 00:00:00 2001 From: David Sauve Date: Tue, 10 Nov 2009 20:45:37 -0500 Subject: [PATCH 05/98] Passing first two tests... --- tests/xapian_tests/tests/xapian_query.py | 4 ++-- xapian_backend.py | 22 ++++++++-------------- 2 files changed, 10 insertions(+), 16 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index 4ec3ee5..4affe50 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -49,8 +49,8 @@ class XapianSearchQueryTestCase(TestCase): settings.HAYSTACK_XAPIAN_PATH = self.old_xapian_path super(XapianSearchQueryTestCase, self).tearDown() - # def test_build_query_all(self): - # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query()') + def test_build_query_all(self): + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query()') def test_build_query_single_word(self): self.sq.add_filter(SQ(content='hello')) diff --git a/xapian_backend.py b/xapian_backend.py index 16725f6..bee95c9 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -934,21 +934,15 @@ class SearchQuery(BaseSearchQuery): super(SearchQuery, self).__init__(backend=backend) self.backend = backend or SearchBackend() - def as_xapian_query(self, parent, query_fragment_callback): - query_list = [] - - for child in parent.children: - if hasattr(child, 'as_query_string'): - query_list.append(self.as_xapian_query(child, query_fragment_callback)) - else: - expression, value = child - field, filter_type = self.query_filter.split_expression(expression) - query_list.append(query_fragment_callback(field, filter_type, value)) - - return xapian.Query(xapian.Query.OP_AND, query_list) - def build_query(self): - query = self.as_xapian_query(self.query_filter, self.build_query_fragment) + if not self.query_filter: + query = xapian.Query('') + else: + for child in self.query_filter.children: + expression, value = child + query = xapian.Query(value) + + return query def build_query_fragment(self, field, filter_type, value): return xapian.Query(value) From 048e296d651781782b906ed2beb2c101680828f4 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Tue, 10 Nov 2009 20:47:59 -0500 Subject: [PATCH 06/98] Passing three tests. Empty query, single content value, multi-content values --- tests/xapian_tests/tests/xapian_query.py | 10 +++++----- xapian_backend.py | 6 +++++- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index 4affe50..da09a0b 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -56,11 +56,11 @@ class XapianSearchQueryTestCase(TestCase): self.sq.add_filter(SQ(content='hello')) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(hello)') - # def test_build_query_multiple_words_and(self): - # self.sq.add_filter(SQ(content='hello')) - # self.sq.add_filter(SQ(content='world')) - # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND world))') - # + def test_build_query_multiple_words_and(self): + self.sq.add_filter(SQ(content='hello')) + self.sq.add_filter(SQ(content='world')) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND world))') + # def test_build_query_multiple_words_not(self): # self.sq.add_filter(~SQ(content='hello')) # self.sq.add_filter(~SQ(content='world')) diff --git a/xapian_backend.py b/xapian_backend.py index bee95c9..b4e4b73 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -938,9 +938,13 @@ class SearchQuery(BaseSearchQuery): if not self.query_filter: query = xapian.Query('') else: + query_list = [] + for child in self.query_filter.children: expression, value = child - query = xapian.Query(value) + query_list.append(value) + + query = xapian.Query(xapian.Query.OP_AND, query_list) return query From 5c67f5476a91b302c900614723f8cb84a4d97d95 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Tue, 10 Nov 2009 21:31:25 -0500 Subject: [PATCH 07/98] Four tests passing now. Recursively parsing the search nodes and negated on NOT as required. --- tests/xapian_tests/tests/xapian_query.py | 8 ++--- xapian_backend.py | 39 ++++++++++++++++-------- 2 files changed, 30 insertions(+), 17 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index da09a0b..54d4e57 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -61,10 +61,10 @@ class XapianSearchQueryTestCase(TestCase): self.sq.add_filter(SQ(content='world')) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND world))') - # def test_build_query_multiple_words_not(self): - # self.sq.add_filter(~SQ(content='hello')) - # self.sq.add_filter(~SQ(content='world')) - # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((NOT hello NOT world))') + def test_build_query_multiple_words_not(self): + self.sq.add_filter(~SQ(content='hello')) + self.sq.add_filter(~SQ(content='world')) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((( AND_NOT hello) AND ( AND_NOT world)))') # def test_build_query_multiple_words_or(self): # self.sq.add_filter('content', 'hello', use_or=True) diff --git a/xapian_backend.py b/xapian_backend.py index b4e4b73..6585225 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -15,7 +15,7 @@ # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. __author__ = 'David Sauve' -__version__ = (1, 0, 0, 'beta') +__version__ = (2, 0, 0, 'alpha') import datetime import cPickle as pickle @@ -29,7 +29,7 @@ from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.encoding import smart_unicode, force_unicode -from haystack.backends import BaseSearchBackend, BaseSearchQuery, log_query +from haystack.backends import BaseSearchBackend, BaseSearchQuery, SearchNode, log_query from haystack.exceptions import MissingDependency from haystack.fields import DateField, DateTimeField, IntegerField, FloatField, BooleanField, MultiValueField from haystack.models import SearchResult @@ -936,19 +936,32 @@ class SearchQuery(BaseSearchQuery): def build_query(self): if not self.query_filter: - query = xapian.Query('') + return xapian.Query('') else: - query_list = [] - - for child in self.query_filter.children: - expression, value = child - query_list.append(value) - - query = xapian.Query(xapian.Query.OP_AND, query_list) - - return query + return self._query_from_search_node(self.query_filter) - def build_query_fragment(self, field, filter_type, value): + def _query_from_search_node(self, search_node, is_not=False): + query_list = [] + + for child in search_node.children: + if isinstance(child, SearchNode): + query_list.append( + xapian.Query( + xapian.Query.OP_AND, + self._query_from_search_node(child, child.negated) + ) + ) + else: + expression, value = child + if is_not: + # DS_TODO: This can almost definitely be improved. + query_list.append(xapian.Query(xapian.Query.OP_AND_NOT, '', value)) + else: + query_list.append(xapian.Query(value)) + + return xapian.Query(xapian.Query.OP_AND, query_list) + + def build_sub_query(self, value): return xapian.Query(value) # From 132e13e66688cb20ae02db163a1ec89a3124f70a Mon Sep 17 00:00:00 2001 From: David Sauve Date: Tue, 10 Nov 2009 21:45:49 -0500 Subject: [PATCH 08/98] Five tests. OR operator now working --- tests/xapian_tests/tests/xapian_query.py | 9 ++++----- xapian_backend.py | 9 +++++++-- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index 54d4e57..db6e7b0 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -66,11 +66,10 @@ class XapianSearchQueryTestCase(TestCase): self.sq.add_filter(~SQ(content='world')) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((( AND_NOT hello) AND ( AND_NOT world)))') - # def test_build_query_multiple_words_or(self): - # self.sq.add_filter('content', 'hello', use_or=True) - # self.sq.add_filter('content', 'world', use_or=True) - # self.assertEqual(self.sq.build_query(), 'hello OR world') - # + def test_build_query_multiple_words_or(self): + self.sq.add_filter(SQ(content='hello') | SQ(content='world')) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello OR world))') + # def test_build_query_multiple_words_mixed(self): # self.sq.add_filter('content', 'why') # self.sq.add_filter('content', 'hello', use_or=True) diff --git a/xapian_backend.py b/xapian_backend.py index 6585225..f87bd70 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -948,7 +948,9 @@ class SearchQuery(BaseSearchQuery): query_list.append( xapian.Query( xapian.Query.OP_AND, - self._query_from_search_node(child, child.negated) + self._query_from_search_node( + child, child.negated + ) ) ) else: @@ -959,7 +961,10 @@ class SearchQuery(BaseSearchQuery): else: query_list.append(xapian.Query(value)) - return xapian.Query(xapian.Query.OP_AND, query_list) + if search_node.connector == 'OR': + return xapian.Query(xapian.Query.OP_OR, query_list) + else: + return xapian.Query(xapian.Query.OP_AND, query_list) def build_sub_query(self, value): return xapian.Query(value) From b740066f43d6e2edac13cfffc156a021ff239d07 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Tue, 10 Nov 2009 21:53:32 -0500 Subject: [PATCH 09/98] Six passing tests. Combining AND, OR, NOT works. --- tests/xapian_tests/tests/xapian_query.py | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index db6e7b0..ea5eb46 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -70,12 +70,11 @@ class XapianSearchQueryTestCase(TestCase): self.sq.add_filter(SQ(content='hello') | SQ(content='world')) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello OR world))') - # def test_build_query_multiple_words_mixed(self): - # self.sq.add_filter('content', 'why') - # self.sq.add_filter('content', 'hello', use_or=True) - # self.sq.add_filter('content', 'world', use_not=True) - # self.assertEqual(self.sq.build_query(), 'why OR hello NOT world') - # + def test_build_query_multiple_words_mixed(self): + self.sq.add_filter(SQ(content='why') | SQ(content='hello')) + self.sq.add_filter(~SQ(content='world')) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(((why OR hello) AND ( AND_NOT world)))') + # def test_build_query_phrase(self): # self.sq.add_filter('content', 'hello world') # self.assertEqual(self.sq.build_query(), '"hello world"') From 45a6883028fb1ee64dbf2c20c42b3a4aa96af4dc Mon Sep 17 00:00:00 2001 From: David Sauve Date: Wed, 21 Oct 2009 08:41:27 -0400 Subject: [PATCH 10/98] Started work in refactor --- tests/xapian_tests/tests/__init__.py | 2 +- tests/xapian_tests/tests/xapian_query.py | 134 +++++++++++------------ xapian_backend.py | 52 +++------ 3 files changed, 82 insertions(+), 106 deletions(-) diff --git a/tests/xapian_tests/tests/__init__.py b/tests/xapian_tests/tests/__init__.py index 25b3a6f..5b721c7 100644 --- a/tests/xapian_tests/tests/__init__.py +++ b/tests/xapian_tests/tests/__init__.py @@ -18,4 +18,4 @@ import warnings warnings.simplefilter('ignore', Warning) from xapian_tests.tests.xapian_query import * -from xapian_tests.tests.xapian_backend import * +# from xapian_tests.tests.xapian_backend import * diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index ecd96ec..44d0862 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -50,78 +50,78 @@ class XapianSearchQueryTestCase(TestCase): super(XapianSearchQueryTestCase, self).tearDown() def test_build_query_all(self): - self.assertEqual(self.sq.build_query(), '*') - + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query()') + def test_build_query_single_word(self): self.sq.add_filter(SQ(content='hello')) - self.assertEqual(self.sq.build_query(), 'hello') - + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(hello)') + def test_build_query_multiple_words_and(self): self.sq.add_filter(SQ(content='hello')) self.sq.add_filter(SQ(content='world')) - self.assertEqual(self.sq.build_query(), '(hello AND world)') - + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND world))') + def test_build_query_multiple_words_not(self): self.sq.add_filter(~SQ(content='hello')) self.sq.add_filter(~SQ(content='world')) - self.assertEqual(self.sq.build_query(), '(NOT (hello) AND NOT (world))') - - def test_build_query_multiple_words_or(self): - self.sq.add_filter(SQ(content='hello'), use_or=True) - self.sq.add_filter(SQ(content='world'), use_or=True) - self.assertEqual(self.sq.build_query(), '(hello OR world)') - - def test_build_query_multiple_words_mixed(self): - self.sq.add_filter(SQ(content='why')) - self.sq.add_filter(SQ(content='hello'), use_or=True) - self.sq.add_filter(~SQ(content='world')) - self.assertEqual(self.sq.build_query(), '((why OR hello) AND NOT (world))') - - def test_build_query_phrase(self): - self.sq.add_filter(SQ(content='hello world')) - self.assertEqual(self.sq.build_query(), '"hello world"') - - def test_build_query_multiple_filter_types(self): - self.sq.add_filter(SQ(content='why')) - self.sq.add_filter(SQ(pub_date__lte=datetime.datetime(2009, 2, 10, 1, 59))) - self.sq.add_filter(SQ(author__gt='david')) - self.sq.add_filter(SQ(created__lt=datetime.datetime(2009, 2, 12, 12, 13))) - self.sq.add_filter(SQ(title__gte='B')) - self.sq.add_filter(SQ(id__in=[1, 2, 3])) - self.assertEqual(self.sq.build_query(), '(why AND pub_date:..20090210015900 AND NOT author:..david AND NOT created:20090212121300..* AND title:B..* AND (id:1 OR id:2 OR id:3))') - - def test_build_query_multiple_exclude_types(self): - self.sq.add_filter(~SQ(content='why')) - self.sq.add_filter(~SQ(pub_date__lte=datetime.datetime(2009, 2, 10, 1, 59))) - self.sq.add_filter(~SQ(author__gt='david')) - self.sq.add_filter(~SQ(created__lt=datetime.datetime(2009, 2, 12, 12, 13))) - self.sq.add_filter(~SQ(title__gte='B')) - self.sq.add_filter(~SQ(id__in=[1, 2, 3])) - self.assertEqual(self.sq.build_query(), '(NOT (why) AND NOT (pub_date:..20090210015900) AND NOT (NOT author:..david) AND NOT (NOT created:20090212121300..*) AND NOT (title:B..*) AND NOT ((id:1 OR id:2 OR id:3)))') - - def test_build_query_wildcard_filter_types(self): - self.sq.add_filter(SQ(content='why')) - self.sq.add_filter(SQ(title__startswith='haystack')) - self.assertEqual(self.sq.build_query(), '(why AND title:haystack*)') - - def test_clean(self): - self.assertEqual(self.sq.clean('hello world'), 'hello world') - self.assertEqual(self.sq.clean('hello AND world'), 'hello and world') - self.assertEqual(self.sq.clean('hello AND OR NOT + - && || ! ( ) { } [ ] ^ " ~ * ? : \ world'), 'hello and or not \\+ \\- \\&& \\|| \\! \\( \\) \\{ \\} \\[ \\] \\^ \\" \\~ \\* \\? \\: \\\\ world') - self.assertEqual(self.sq.clean('so please NOTe i am in a bAND and bORed'), 'so please NOTe i am in a bAND and bORed') - - def test_build_query_with_models(self): - self.sq.add_filter(SQ(content='hello')) - self.sq.add_model(MockModel) - self.assertEqual(self.sq.build_query(), u'(hello) AND (django_ct:core.mockmodel)') - - self.sq.add_model(AnotherMockModel) - self.assertEqual(self.sq.build_query(), u'(hello) AND (django_ct:core.anothermockmodel OR django_ct:core.mockmodel)') - - def test_build_query_with_datetime(self): - self.sq.add_filter(SQ(pub_date=datetime.datetime(2009, 5, 9, 16, 20))) - self.assertEqual(self.sq.build_query(), u'pub_date:20090509162000') - - def test_build_query_with_sequence_and_filter_not_in(self): - self.sq.add_filter(SQ(id__exact=[1, 2, 3])) - self.assertEqual(self.sq.build_query(), u'id:[1, 2, 3]') \ No newline at end of file + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((NOT hello NOT world))') + + # def test_build_query_multiple_words_or(self): + # self.sq.add_filter('content', 'hello', use_or=True) + # self.sq.add_filter('content', 'world', use_or=True) + # self.assertEqual(self.sq.build_query(), 'hello OR world') + # + # def test_build_query_multiple_words_mixed(self): + # self.sq.add_filter('content', 'why') + # self.sq.add_filter('content', 'hello', use_or=True) + # self.sq.add_filter('content', 'world', use_not=True) + # self.assertEqual(self.sq.build_query(), 'why OR hello NOT world') + # + # def test_build_query_phrase(self): + # self.sq.add_filter('content', 'hello world') + # self.assertEqual(self.sq.build_query(), '"hello world"') + # + # def test_build_query_multiple_filter_types(self): + # self.sq.add_filter('content', 'why') + # self.sq.add_filter('pub_date__lte', datetime.datetime(2009, 2, 10, 1, 59)) + # self.sq.add_filter('author__gt', 'david') + # self.sq.add_filter('created__lt', datetime.datetime(2009, 2, 12, 12, 13)) + # self.sq.add_filter('title__gte', 'B') + # self.sq.add_filter('id__in', [1, 2, 3]) + # self.assertEqual(self.sq.build_query(), 'why AND pub_date:..20090210015900 AND NOT author:..david AND NOT created:20090212121300..* AND title:B..* AND (id:1 OR id:2 OR id:3)') + # + # def test_build_query_multiple_exclude_types(self): + # self.sq.add_filter('content', 'why', use_not=True) + # self.sq.add_filter('pub_date__lte', datetime.datetime(2009, 2, 10, 1, 59), use_not=True) + # self.sq.add_filter('author__gt', 'david', use_not=True) + # self.sq.add_filter('created__lt', datetime.datetime(2009, 2, 12, 12, 13), use_not=True) + # self.sq.add_filter('title__gte', 'B', use_not=True) + # self.sq.add_filter('id__in', [1, 2, 3], use_not=True) + # self.assertEqual(self.sq.build_query(), 'NOT why AND NOT pub_date:..20090210015900 AND author:..david AND created:20090212121300..* AND NOT title:B..* AND NOT id:1 NOT id:2 NOT id:3') + # + # def test_build_query_wildcard_filter_types(self): + # self.sq.add_filter('content', 'why') + # self.sq.add_filter('title__startswith', 'haystack') + # self.assertEqual(self.sq.build_query(), 'why AND title:haystack*') + # + # def test_clean(self): + # self.assertEqual(self.sq.clean('hello world'), 'hello world') + # self.assertEqual(self.sq.clean('hello AND world'), 'hello and world') + # self.assertEqual(self.sq.clean('hello AND OR NOT + - && || ! ( ) { } [ ] ^ " ~ * ? : \ world'), 'hello and or not \\+ \\- \\&& \\|| \\! \\( \\) \\{ \\} \\[ \\] \\^ \\" \\~ \\* \\? \\: \\\\ world') + # self.assertEqual(self.sq.clean('so please NOTe i am in a bAND and bORed'), 'so please NOTe i am in a bAND and bORed') + # + # def test_build_query_with_models(self): + # self.sq.add_filter('content', 'hello') + # self.sq.add_model(MockModel) + # self.assertEqual(self.sq.build_query(), u'(hello) django_ct:core.mockmodel') + # + # self.sq.add_model(AnotherMockModel) + # self.assertEqual(self.sq.build_query(), u'(hello) django_ct:core.anothermockmodel django_ct:core.mockmodel') + # + # def test_build_query_with_datetime(self): + # self.sq.add_filter('pub_date', datetime.datetime(2009, 5, 9, 16, 20)) + # self.assertEqual(self.sq.build_query(), u'pub_date:20090509162000') + # + # def test_build_query_with_sequence_and_filter_not_in(self): + # self.sq.add_filter('id__exact', [1, 2, 3]) + # self.assertEqual(self.sq.build_query(), u'id:[1, 2, 3]') diff --git a/xapian_backend.py b/xapian_backend.py index 2f48b6e..dc19d3e 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -933,46 +933,22 @@ class SearchQuery(BaseSearchQuery): super(SearchQuery, self).__init__(backend=backend) self.backend = backend or SearchBackend() - def build_query_fragment(self, field, filter_type, value): - """ - Builds a search query fragment from a field, filter type and value. - Returns: - A query string fragment suitable for parsing by Xapian. - """ - result = '' + def build_query(self): + if not self.query_filter: + return xapian.Query('') - if not isinstance(value, (list, tuple)): - # Convert whatever we find to what xapian wants. - value = self.backend._marshal_value(value) - - # Check to see if it's a phrase for an exact match. - if ' ' in value: - value = '"%s"' % value - - # 'content' is a special reserved word, much like 'pk' in - # Django's ORM layer. It indicates 'no special field'. - if field == 'content': - result = value - else: - filter_types = { - 'exact': '%s:%s', - 'gte': '%s:%s..*', - 'gt': 'NOT %s:..%s', - 'lte': '%s:..%s', - 'lt': 'NOT %s:%s..*', - 'startswith': '%s:%s*', - } - - if filter_type != 'in': - result = filter_types[filter_type] % (field, value) - else: - in_options = [] - for possible_value in value: - in_options.append('%s:%s' % (field, possible_value)) - result = '(%s)' % ' OR '.join(in_options) - - return result + values = [] + for child in self.query_filter.children: + if isinstance(child, self.query_filter.__class__): + print 'SQ: ', child # TODO: Recursive call down tree... + else: + expression, value = child + field, filter_type = self.query_filter.split_expression(expression) + values.append(value) + + return xapian.Query(xapian.Query.OP_AND, values) + def run(self, spelling_query=None): """ Builds and executes the query. Returns a list of search results. From 6e7fc1d6c6ac3aa43e46c0563a79e465190bb6d5 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Wed, 21 Oct 2009 16:20:17 -0400 Subject: [PATCH 11/98] More changes to build_query --- xapian_backend.py | 50 +++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 44 insertions(+), 6 deletions(-) diff --git a/xapian_backend.py b/xapian_backend.py index dc19d3e..b8b5ffe 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -934,11 +934,9 @@ class SearchQuery(BaseSearchQuery): self.backend = backend or SearchBackend() def build_query(self): - if not self.query_filter: - return xapian.Query('') - values = [] - + + return final_query for child in self.query_filter.children: if isinstance(child, self.query_filter.__class__): print 'SQ: ', child # TODO: Recursive call down tree... @@ -946,9 +944,49 @@ class SearchQuery(BaseSearchQuery): expression, value = child field, filter_type = self.query_filter.split_expression(expression) values.append(value) - + return xapian.Query(xapian.Query.OP_AND, values) - + + def build_query_fragment(self, field, filter_type, value): + """ + Builds a search query fragment from a field, filter type and value. + Returns: + A query string fragment suitable for parsing by Xapian. + """ + result = '' + + if not isinstance(value, (list, tuple)): + # Convert whatever we find to what xapian wants. + value = self.backend._marshal_value(value) + + # Check to see if it's a phrase for an exact match. + if ' ' in value: + value = '"%s"' % value + + # 'content' is a special reserved word, much like 'pk' in + # Django's ORM layer. It indicates 'no special field'. + if field == 'content': + result = value + else: + filter_types = { + 'exact': '%s:%s', + 'gte': '%s:%s..*', + 'gt': 'NOT %s:..%s', + 'lte': '%s:..%s', + 'lt': 'NOT %s:%s..*', + 'startswith': '%s:%s*', + } + + if filter_type != 'in': + result = filter_types[filter_type] % (field, value) + else: + in_options = [] + for possible_value in value: + in_options.append('%s:%s' % (field, possible_value)) + result = '(%s)' % ' OR '.join(in_options) + + return result + def run(self, spelling_query=None): """ Builds and executes the query. Returns a list of search results. From b16859121f27cf5711aa388a941d939342acff98 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Tue, 27 Oct 2009 22:03:04 -0400 Subject: [PATCH 12/98] Work on refactoring. Eliminated a lot of useless code and started to implement build_query using xapian.Query --- xapian_backend.py | 175 +++++++++++++++------------------------------- 1 file changed, 57 insertions(+), 118 deletions(-) diff --git a/xapian_backend.py b/xapian_backend.py index b8b5ffe..111ad82 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -932,125 +932,64 @@ class SearchQuery(BaseSearchQuery): """ super(SearchQuery, self).__init__(backend=backend) self.backend = backend or SearchBackend() - + def build_query(self): - values = [] - - return final_query - for child in self.query_filter.children: - if isinstance(child, self.query_filter.__class__): - print 'SQ: ', child # TODO: Recursive call down tree... - else: - expression, value = child - field, filter_type = self.query_filter.split_expression(expression) - values.append(value) - - return xapian.Query(xapian.Query.OP_AND, values) - - def build_query_fragment(self, field, filter_type, value): - """ - Builds a search query fragment from a field, filter type and value. - Returns: - A query string fragment suitable for parsing by Xapian. - """ - result = '' - - if not isinstance(value, (list, tuple)): - # Convert whatever we find to what xapian wants. - value = self.backend._marshal_value(value) - - # Check to see if it's a phrase for an exact match. - if ' ' in value: - value = '"%s"' % value - - # 'content' is a special reserved word, much like 'pk' in - # Django's ORM layer. It indicates 'no special field'. - if field == 'content': - result = value + if not self.query_filter.children: + return xapian.Query('') else: - filter_types = { - 'exact': '%s:%s', - 'gte': '%s:%s..*', - 'gt': 'NOT %s:..%s', - 'lte': '%s:..%s', - 'lt': 'NOT %s:%s..*', - 'startswith': '%s:%s*', - } + query_list = [] + + for child in self.query_filter.children: + if isinstance(child, self.query_filter.__class__): + pass + else: + expression, value = child + field, filter_type = self.query_filter.split_expression(expression) + query_list.append(xapian.Query(value)) + + return xapian.Query(xapian.Query.OP_AND, query_list) + - if filter_type != 'in': - result = filter_types[filter_type] % (field, value) - else: - in_options = [] - for possible_value in value: - in_options.append('%s:%s' % (field, possible_value)) - result = '(%s)' % ' OR '.join(in_options) - - return result - - def run(self, spelling_query=None): - """ - Builds and executes the query. Returns a list of search results. - - Returns: - List of search results - """ - final_query = self.build_query() - kwargs = { - 'start_offset': self.start_offset, - } - - if self.order_by: - kwargs['sort_by'] = self.order_by - - if self.end_offset is not None: - kwargs['end_offset'] = self.end_offset - self.start_offset - - if self.highlight: - kwargs['highlight'] = self.highlight - - if self.facets: - kwargs['facets'] = list(self.facets) - - if self.date_facets: - kwargs['date_facets'] = self.date_facets - - if self.query_facets: - kwargs['query_facets'] = self.query_facets - - if self.narrow_queries: - kwargs['narrow_queries'] = self.narrow_queries - - if spelling_query: - kwargs['spelling_query'] = spelling_query - - if self.boost: - kwargs['boost'] = self.boost - - results = self.backend.search(final_query, **kwargs) - self._results = results.get('results', []) - self._hit_count = results.get('hits', 0) - self._facet_counts = results.get('facets', {}) - self._spelling_suggestion = results.get('spelling_suggestion', None) + # def build_query_fragment(self, field, filter_type, value): + # print 'field: ', field + # print 'filter_type: ', filter_type + # print 'value: ', value - def run_mlt(self): - """ - Builds and executes the query. Returns a list of search results. - - Returns: - List of search results - """ - if self._more_like_this is False or self._mlt_instance is None: - raise MoreLikeThisError("No instance was provided to determine 'More Like This' results.") - - additional_query_string = self.build_query() - kwargs = { - 'start_offset': self.start_offset, - } - - if self.end_offset is not None: - kwargs['end_offset'] = self.end_offset - self.start_offset - - results = self.backend.more_like_this(self._mlt_instance, additional_query_string, **kwargs) - self._results = results.get('results', []) - self._hit_count = results.get('hits', 0) - + # """ + # Builds a search query fragment from a field, filter type and value. + # Returns: + # A query string fragment suitable for parsing by Xapian. + # """ + # result = '' + # + # if not isinstance(value, (list, tuple)): + # # Convert whatever we find to what xapian wants. + # value = self.backend._marshal_value(value) + # + # # Check to see if it's a phrase for an exact match. + # if ' ' in value: + # value = '"%s"' % value + # + # # 'content' is a special reserved word, much like 'pk' in + # # Django's ORM layer. It indicates 'no special field'. + # if field == 'content': + # result = value + # else: + # filter_types = { + # 'exact': '%s:%s', + # 'gte': '%s:%s..*', + # 'gt': 'NOT %s:..%s', + # 'lte': '%s:..%s', + # 'lt': 'NOT %s:%s..*', + # 'startswith': '%s:%s*', + # } + # + # if filter_type != 'in': + # result = filter_types[filter_type] % (field, value) + # else: + # in_options = [] + # for possible_value in value: + # in_options.append('%s:%s' % (field, possible_value)) + # result = '(%s)' % ' OR '.join(in_options) + # + # return result From 9bbd3f32eacd0b597cc35e6e30a8e0096a93040b Mon Sep 17 00:00:00 2001 From: David Sauve Date: Mon, 9 Nov 2009 20:01:20 -0500 Subject: [PATCH 13/98] More refactor work --- tests/xapian_tests/tests/xapian_query.py | 22 +++++------ xapian_backend.py | 48 ++++++++++++++++-------- 2 files changed, 44 insertions(+), 26 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index 44d0862..d89eaa7 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -49,22 +49,22 @@ class XapianSearchQueryTestCase(TestCase): settings.HAYSTACK_XAPIAN_PATH = self.old_xapian_path super(XapianSearchQueryTestCase, self).tearDown() - def test_build_query_all(self): - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query()') + # def test_build_query_all(self): + # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query()') def test_build_query_single_word(self): self.sq.add_filter(SQ(content='hello')) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(hello)') - def test_build_query_multiple_words_and(self): - self.sq.add_filter(SQ(content='hello')) - self.sq.add_filter(SQ(content='world')) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND world))') - - def test_build_query_multiple_words_not(self): - self.sq.add_filter(~SQ(content='hello')) - self.sq.add_filter(~SQ(content='world')) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((NOT hello NOT world))') + # def test_build_query_multiple_words_and(self): + # self.sq.add_filter(SQ(content='hello')) + # self.sq.add_filter(SQ(content='world')) + # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND world))') + # + # def test_build_query_multiple_words_not(self): + # self.sq.add_filter(~SQ(content='hello')) + # self.sq.add_filter(~SQ(content='world')) + # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((NOT hello NOT world))') # def test_build_query_multiple_words_or(self): # self.sq.add_filter('content', 'hello', use_or=True) diff --git a/xapian_backend.py b/xapian_backend.py index 111ad82..ced5791 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -932,24 +932,42 @@ class SearchQuery(BaseSearchQuery): """ super(SearchQuery, self).__init__(backend=backend) self.backend = backend or SearchBackend() + + def as_xapian_query(self, parent, query_fragment_callback): + query_list = [] + + for child in parent.children: + if hasattr(child, 'as_query_string'): + query_list.append(self.as_xapian_query(child, query_fragment_callback)) + else: + expression, value = child + field, filter_type = self.query_filter.split_expression(expression) + query_list.append(query_fragment_callback(field, filter_type, value)) + + return xapian.Query(xapian.Query.OP_AND, query_list) def build_query(self): - if not self.query_filter.children: - return xapian.Query('') - else: - query_list = [] - - for child in self.query_filter.children: - if isinstance(child, self.query_filter.__class__): - pass - else: - expression, value = child - field, filter_type = self.query_filter.split_expression(expression) - query_list.append(xapian.Query(value)) - - return xapian.Query(xapian.Query.OP_AND, query_list) - + query = self.as_xapian_query(self.query_filter, self.build_query_fragment) + def build_query_fragment(self, field, filter_type, value): + return xapian.Query(value) + + # + # if not self.query_filter.children: + # return xapian.Query('') + # else: + # query_list = [] + # + # for child in self.query_filter.children: + # if isinstance(child, self.query_filter.__class__): + # query_list.append(self.build_query(child)) + # else: + # expression, value = child + # field, filter_type = self.query_filter.split_expression(expression) + # query_list.append(xapian.Query(value)) + # + # return xapian.Query(xapian.Query.OP_AND, query_list) + # def build_query_fragment(self, field, filter_type, value): # print 'field: ', field # print 'filter_type: ', filter_type From 3a85a952011d0441094dd4d62c6dbd4f8468576a Mon Sep 17 00:00:00 2001 From: David Sauve Date: Tue, 10 Nov 2009 20:45:37 -0500 Subject: [PATCH 14/98] Passing first two tests... --- tests/xapian_tests/tests/xapian_query.py | 4 ++-- xapian_backend.py | 22 ++++++++-------------- 2 files changed, 10 insertions(+), 16 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index d89eaa7..b94b7f5 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -49,8 +49,8 @@ class XapianSearchQueryTestCase(TestCase): settings.HAYSTACK_XAPIAN_PATH = self.old_xapian_path super(XapianSearchQueryTestCase, self).tearDown() - # def test_build_query_all(self): - # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query()') + def test_build_query_all(self): + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query()') def test_build_query_single_word(self): self.sq.add_filter(SQ(content='hello')) diff --git a/xapian_backend.py b/xapian_backend.py index ced5791..8c86ac0 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -933,21 +933,15 @@ class SearchQuery(BaseSearchQuery): super(SearchQuery, self).__init__(backend=backend) self.backend = backend or SearchBackend() - def as_xapian_query(self, parent, query_fragment_callback): - query_list = [] - - for child in parent.children: - if hasattr(child, 'as_query_string'): - query_list.append(self.as_xapian_query(child, query_fragment_callback)) - else: - expression, value = child - field, filter_type = self.query_filter.split_expression(expression) - query_list.append(query_fragment_callback(field, filter_type, value)) - - return xapian.Query(xapian.Query.OP_AND, query_list) - def build_query(self): - query = self.as_xapian_query(self.query_filter, self.build_query_fragment) + if not self.query_filter: + query = xapian.Query('') + else: + for child in self.query_filter.children: + expression, value = child + query = xapian.Query(value) + + return query def build_query_fragment(self, field, filter_type, value): return xapian.Query(value) From 097d1f0c77c039a0f11cd37f81902735eaa48e79 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Tue, 10 Nov 2009 20:47:59 -0500 Subject: [PATCH 15/98] Passing three tests. Empty query, single content value, multi-content values --- tests/xapian_tests/tests/xapian_query.py | 10 +++++----- xapian_backend.py | 6 +++++- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index b94b7f5..a3a5cbd 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -56,11 +56,11 @@ class XapianSearchQueryTestCase(TestCase): self.sq.add_filter(SQ(content='hello')) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(hello)') - # def test_build_query_multiple_words_and(self): - # self.sq.add_filter(SQ(content='hello')) - # self.sq.add_filter(SQ(content='world')) - # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND world))') - # + def test_build_query_multiple_words_and(self): + self.sq.add_filter(SQ(content='hello')) + self.sq.add_filter(SQ(content='world')) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND world))') + # def test_build_query_multiple_words_not(self): # self.sq.add_filter(~SQ(content='hello')) # self.sq.add_filter(~SQ(content='world')) diff --git a/xapian_backend.py b/xapian_backend.py index 8c86ac0..1d16ac5 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -937,9 +937,13 @@ class SearchQuery(BaseSearchQuery): if not self.query_filter: query = xapian.Query('') else: + query_list = [] + for child in self.query_filter.children: expression, value = child - query = xapian.Query(value) + query_list.append(value) + + query = xapian.Query(xapian.Query.OP_AND, query_list) return query From eb9c4f9777a2b26024e6bdbd2b8a94e2c8f1b135 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Tue, 10 Nov 2009 21:31:25 -0500 Subject: [PATCH 16/98] Four tests passing now. Recursively parsing the search nodes and negated on NOT as required. --- tests/xapian_tests/tests/xapian_query.py | 8 ++--- xapian_backend.py | 39 ++++++++++++++++-------- 2 files changed, 30 insertions(+), 17 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index a3a5cbd..0509f2d 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -61,10 +61,10 @@ class XapianSearchQueryTestCase(TestCase): self.sq.add_filter(SQ(content='world')) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND world))') - # def test_build_query_multiple_words_not(self): - # self.sq.add_filter(~SQ(content='hello')) - # self.sq.add_filter(~SQ(content='world')) - # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((NOT hello NOT world))') + def test_build_query_multiple_words_not(self): + self.sq.add_filter(~SQ(content='hello')) + self.sq.add_filter(~SQ(content='world')) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((( AND_NOT hello) AND ( AND_NOT world)))') # def test_build_query_multiple_words_or(self): # self.sq.add_filter('content', 'hello', use_or=True) diff --git a/xapian_backend.py b/xapian_backend.py index 1d16ac5..7379469 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -15,7 +15,7 @@ # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. __author__ = 'David Sauve' -__version__ = (1, 0, 0, 'beta') +__version__ = (2, 0, 0, 'alpha') import time import datetime @@ -30,7 +30,7 @@ from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.encoding import smart_unicode, force_unicode -from haystack.backends import BaseSearchBackend, BaseSearchQuery, log_query +from haystack.backends import BaseSearchBackend, BaseSearchQuery, SearchNode, log_query from haystack.exceptions import MissingDependency from haystack.fields import DateField, DateTimeField, IntegerField, FloatField, BooleanField, MultiValueField from haystack.models import SearchResult @@ -935,19 +935,32 @@ class SearchQuery(BaseSearchQuery): def build_query(self): if not self.query_filter: - query = xapian.Query('') + return xapian.Query('') else: - query_list = [] - - for child in self.query_filter.children: - expression, value = child - query_list.append(value) - - query = xapian.Query(xapian.Query.OP_AND, query_list) - - return query + return self._query_from_search_node(self.query_filter) - def build_query_fragment(self, field, filter_type, value): + def _query_from_search_node(self, search_node, is_not=False): + query_list = [] + + for child in search_node.children: + if isinstance(child, SearchNode): + query_list.append( + xapian.Query( + xapian.Query.OP_AND, + self._query_from_search_node(child, child.negated) + ) + ) + else: + expression, value = child + if is_not: + # DS_TODO: This can almost definitely be improved. + query_list.append(xapian.Query(xapian.Query.OP_AND_NOT, '', value)) + else: + query_list.append(xapian.Query(value)) + + return xapian.Query(xapian.Query.OP_AND, query_list) + + def build_sub_query(self, value): return xapian.Query(value) # From 31af86049288625dace4de571de3d656d665b563 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Tue, 10 Nov 2009 21:45:49 -0500 Subject: [PATCH 17/98] Five tests. OR operator now working --- tests/xapian_tests/tests/xapian_query.py | 9 ++++----- xapian_backend.py | 9 +++++++-- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index 0509f2d..189881f 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -66,11 +66,10 @@ class XapianSearchQueryTestCase(TestCase): self.sq.add_filter(~SQ(content='world')) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((( AND_NOT hello) AND ( AND_NOT world)))') - # def test_build_query_multiple_words_or(self): - # self.sq.add_filter('content', 'hello', use_or=True) - # self.sq.add_filter('content', 'world', use_or=True) - # self.assertEqual(self.sq.build_query(), 'hello OR world') - # + def test_build_query_multiple_words_or(self): + self.sq.add_filter(SQ(content='hello') | SQ(content='world')) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello OR world))') + # def test_build_query_multiple_words_mixed(self): # self.sq.add_filter('content', 'why') # self.sq.add_filter('content', 'hello', use_or=True) diff --git a/xapian_backend.py b/xapian_backend.py index 7379469..442d7fa 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -947,7 +947,9 @@ class SearchQuery(BaseSearchQuery): query_list.append( xapian.Query( xapian.Query.OP_AND, - self._query_from_search_node(child, child.negated) + self._query_from_search_node( + child, child.negated + ) ) ) else: @@ -958,7 +960,10 @@ class SearchQuery(BaseSearchQuery): else: query_list.append(xapian.Query(value)) - return xapian.Query(xapian.Query.OP_AND, query_list) + if search_node.connector == 'OR': + return xapian.Query(xapian.Query.OP_OR, query_list) + else: + return xapian.Query(xapian.Query.OP_AND, query_list) def build_sub_query(self, value): return xapian.Query(value) From b1877db882ff681cc7061eab5ef6ff418d265629 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Tue, 10 Nov 2009 21:53:32 -0500 Subject: [PATCH 18/98] Six passing tests. Combining AND, OR, NOT works. --- tests/xapian_tests/tests/xapian_query.py | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index 189881f..1578829 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -70,12 +70,11 @@ class XapianSearchQueryTestCase(TestCase): self.sq.add_filter(SQ(content='hello') | SQ(content='world')) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello OR world))') - # def test_build_query_multiple_words_mixed(self): - # self.sq.add_filter('content', 'why') - # self.sq.add_filter('content', 'hello', use_or=True) - # self.sq.add_filter('content', 'world', use_not=True) - # self.assertEqual(self.sq.build_query(), 'why OR hello NOT world') - # + def test_build_query_multiple_words_mixed(self): + self.sq.add_filter(SQ(content='why') | SQ(content='hello')) + self.sq.add_filter(~SQ(content='world')) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(((why OR hello) AND ( AND_NOT world)))') + # def test_build_query_phrase(self): # self.sq.add_filter('content', 'hello world') # self.assertEqual(self.sq.build_query(), '"hello world"') From 74adafe2b69100575361a384d44d769031152ac9 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Wed, 21 Oct 2009 08:41:27 -0400 Subject: [PATCH 19/98] Started work in refactor --- tests/xapian_tests/tests/__init__.py | 2 +- tests/xapian_tests/tests/xapian_query.py | 134 +++++++++++------------ xapian_backend.py | 52 +++------ 3 files changed, 82 insertions(+), 106 deletions(-) diff --git a/tests/xapian_tests/tests/__init__.py b/tests/xapian_tests/tests/__init__.py index 25b3a6f..5b721c7 100644 --- a/tests/xapian_tests/tests/__init__.py +++ b/tests/xapian_tests/tests/__init__.py @@ -18,4 +18,4 @@ import warnings warnings.simplefilter('ignore', Warning) from xapian_tests.tests.xapian_query import * -from xapian_tests.tests.xapian_backend import * +# from xapian_tests.tests.xapian_backend import * diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index ecd96ec..44d0862 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -50,78 +50,78 @@ class XapianSearchQueryTestCase(TestCase): super(XapianSearchQueryTestCase, self).tearDown() def test_build_query_all(self): - self.assertEqual(self.sq.build_query(), '*') - + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query()') + def test_build_query_single_word(self): self.sq.add_filter(SQ(content='hello')) - self.assertEqual(self.sq.build_query(), 'hello') - + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(hello)') + def test_build_query_multiple_words_and(self): self.sq.add_filter(SQ(content='hello')) self.sq.add_filter(SQ(content='world')) - self.assertEqual(self.sq.build_query(), '(hello AND world)') - + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND world))') + def test_build_query_multiple_words_not(self): self.sq.add_filter(~SQ(content='hello')) self.sq.add_filter(~SQ(content='world')) - self.assertEqual(self.sq.build_query(), '(NOT (hello) AND NOT (world))') - - def test_build_query_multiple_words_or(self): - self.sq.add_filter(SQ(content='hello'), use_or=True) - self.sq.add_filter(SQ(content='world'), use_or=True) - self.assertEqual(self.sq.build_query(), '(hello OR world)') - - def test_build_query_multiple_words_mixed(self): - self.sq.add_filter(SQ(content='why')) - self.sq.add_filter(SQ(content='hello'), use_or=True) - self.sq.add_filter(~SQ(content='world')) - self.assertEqual(self.sq.build_query(), '((why OR hello) AND NOT (world))') - - def test_build_query_phrase(self): - self.sq.add_filter(SQ(content='hello world')) - self.assertEqual(self.sq.build_query(), '"hello world"') - - def test_build_query_multiple_filter_types(self): - self.sq.add_filter(SQ(content='why')) - self.sq.add_filter(SQ(pub_date__lte=datetime.datetime(2009, 2, 10, 1, 59))) - self.sq.add_filter(SQ(author__gt='david')) - self.sq.add_filter(SQ(created__lt=datetime.datetime(2009, 2, 12, 12, 13))) - self.sq.add_filter(SQ(title__gte='B')) - self.sq.add_filter(SQ(id__in=[1, 2, 3])) - self.assertEqual(self.sq.build_query(), '(why AND pub_date:..20090210015900 AND NOT author:..david AND NOT created:20090212121300..* AND title:B..* AND (id:1 OR id:2 OR id:3))') - - def test_build_query_multiple_exclude_types(self): - self.sq.add_filter(~SQ(content='why')) - self.sq.add_filter(~SQ(pub_date__lte=datetime.datetime(2009, 2, 10, 1, 59))) - self.sq.add_filter(~SQ(author__gt='david')) - self.sq.add_filter(~SQ(created__lt=datetime.datetime(2009, 2, 12, 12, 13))) - self.sq.add_filter(~SQ(title__gte='B')) - self.sq.add_filter(~SQ(id__in=[1, 2, 3])) - self.assertEqual(self.sq.build_query(), '(NOT (why) AND NOT (pub_date:..20090210015900) AND NOT (NOT author:..david) AND NOT (NOT created:20090212121300..*) AND NOT (title:B..*) AND NOT ((id:1 OR id:2 OR id:3)))') - - def test_build_query_wildcard_filter_types(self): - self.sq.add_filter(SQ(content='why')) - self.sq.add_filter(SQ(title__startswith='haystack')) - self.assertEqual(self.sq.build_query(), '(why AND title:haystack*)') - - def test_clean(self): - self.assertEqual(self.sq.clean('hello world'), 'hello world') - self.assertEqual(self.sq.clean('hello AND world'), 'hello and world') - self.assertEqual(self.sq.clean('hello AND OR NOT + - && || ! ( ) { } [ ] ^ " ~ * ? : \ world'), 'hello and or not \\+ \\- \\&& \\|| \\! \\( \\) \\{ \\} \\[ \\] \\^ \\" \\~ \\* \\? \\: \\\\ world') - self.assertEqual(self.sq.clean('so please NOTe i am in a bAND and bORed'), 'so please NOTe i am in a bAND and bORed') - - def test_build_query_with_models(self): - self.sq.add_filter(SQ(content='hello')) - self.sq.add_model(MockModel) - self.assertEqual(self.sq.build_query(), u'(hello) AND (django_ct:core.mockmodel)') - - self.sq.add_model(AnotherMockModel) - self.assertEqual(self.sq.build_query(), u'(hello) AND (django_ct:core.anothermockmodel OR django_ct:core.mockmodel)') - - def test_build_query_with_datetime(self): - self.sq.add_filter(SQ(pub_date=datetime.datetime(2009, 5, 9, 16, 20))) - self.assertEqual(self.sq.build_query(), u'pub_date:20090509162000') - - def test_build_query_with_sequence_and_filter_not_in(self): - self.sq.add_filter(SQ(id__exact=[1, 2, 3])) - self.assertEqual(self.sq.build_query(), u'id:[1, 2, 3]') \ No newline at end of file + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((NOT hello NOT world))') + + # def test_build_query_multiple_words_or(self): + # self.sq.add_filter('content', 'hello', use_or=True) + # self.sq.add_filter('content', 'world', use_or=True) + # self.assertEqual(self.sq.build_query(), 'hello OR world') + # + # def test_build_query_multiple_words_mixed(self): + # self.sq.add_filter('content', 'why') + # self.sq.add_filter('content', 'hello', use_or=True) + # self.sq.add_filter('content', 'world', use_not=True) + # self.assertEqual(self.sq.build_query(), 'why OR hello NOT world') + # + # def test_build_query_phrase(self): + # self.sq.add_filter('content', 'hello world') + # self.assertEqual(self.sq.build_query(), '"hello world"') + # + # def test_build_query_multiple_filter_types(self): + # self.sq.add_filter('content', 'why') + # self.sq.add_filter('pub_date__lte', datetime.datetime(2009, 2, 10, 1, 59)) + # self.sq.add_filter('author__gt', 'david') + # self.sq.add_filter('created__lt', datetime.datetime(2009, 2, 12, 12, 13)) + # self.sq.add_filter('title__gte', 'B') + # self.sq.add_filter('id__in', [1, 2, 3]) + # self.assertEqual(self.sq.build_query(), 'why AND pub_date:..20090210015900 AND NOT author:..david AND NOT created:20090212121300..* AND title:B..* AND (id:1 OR id:2 OR id:3)') + # + # def test_build_query_multiple_exclude_types(self): + # self.sq.add_filter('content', 'why', use_not=True) + # self.sq.add_filter('pub_date__lte', datetime.datetime(2009, 2, 10, 1, 59), use_not=True) + # self.sq.add_filter('author__gt', 'david', use_not=True) + # self.sq.add_filter('created__lt', datetime.datetime(2009, 2, 12, 12, 13), use_not=True) + # self.sq.add_filter('title__gte', 'B', use_not=True) + # self.sq.add_filter('id__in', [1, 2, 3], use_not=True) + # self.assertEqual(self.sq.build_query(), 'NOT why AND NOT pub_date:..20090210015900 AND author:..david AND created:20090212121300..* AND NOT title:B..* AND NOT id:1 NOT id:2 NOT id:3') + # + # def test_build_query_wildcard_filter_types(self): + # self.sq.add_filter('content', 'why') + # self.sq.add_filter('title__startswith', 'haystack') + # self.assertEqual(self.sq.build_query(), 'why AND title:haystack*') + # + # def test_clean(self): + # self.assertEqual(self.sq.clean('hello world'), 'hello world') + # self.assertEqual(self.sq.clean('hello AND world'), 'hello and world') + # self.assertEqual(self.sq.clean('hello AND OR NOT + - && || ! ( ) { } [ ] ^ " ~ * ? : \ world'), 'hello and or not \\+ \\- \\&& \\|| \\! \\( \\) \\{ \\} \\[ \\] \\^ \\" \\~ \\* \\? \\: \\\\ world') + # self.assertEqual(self.sq.clean('so please NOTe i am in a bAND and bORed'), 'so please NOTe i am in a bAND and bORed') + # + # def test_build_query_with_models(self): + # self.sq.add_filter('content', 'hello') + # self.sq.add_model(MockModel) + # self.assertEqual(self.sq.build_query(), u'(hello) django_ct:core.mockmodel') + # + # self.sq.add_model(AnotherMockModel) + # self.assertEqual(self.sq.build_query(), u'(hello) django_ct:core.anothermockmodel django_ct:core.mockmodel') + # + # def test_build_query_with_datetime(self): + # self.sq.add_filter('pub_date', datetime.datetime(2009, 5, 9, 16, 20)) + # self.assertEqual(self.sq.build_query(), u'pub_date:20090509162000') + # + # def test_build_query_with_sequence_and_filter_not_in(self): + # self.sq.add_filter('id__exact', [1, 2, 3]) + # self.assertEqual(self.sq.build_query(), u'id:[1, 2, 3]') diff --git a/xapian_backend.py b/xapian_backend.py index 2f48b6e..dc19d3e 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -933,46 +933,22 @@ class SearchQuery(BaseSearchQuery): super(SearchQuery, self).__init__(backend=backend) self.backend = backend or SearchBackend() - def build_query_fragment(self, field, filter_type, value): - """ - Builds a search query fragment from a field, filter type and value. - Returns: - A query string fragment suitable for parsing by Xapian. - """ - result = '' + def build_query(self): + if not self.query_filter: + return xapian.Query('') - if not isinstance(value, (list, tuple)): - # Convert whatever we find to what xapian wants. - value = self.backend._marshal_value(value) - - # Check to see if it's a phrase for an exact match. - if ' ' in value: - value = '"%s"' % value - - # 'content' is a special reserved word, much like 'pk' in - # Django's ORM layer. It indicates 'no special field'. - if field == 'content': - result = value - else: - filter_types = { - 'exact': '%s:%s', - 'gte': '%s:%s..*', - 'gt': 'NOT %s:..%s', - 'lte': '%s:..%s', - 'lt': 'NOT %s:%s..*', - 'startswith': '%s:%s*', - } - - if filter_type != 'in': - result = filter_types[filter_type] % (field, value) - else: - in_options = [] - for possible_value in value: - in_options.append('%s:%s' % (field, possible_value)) - result = '(%s)' % ' OR '.join(in_options) - - return result + values = [] + for child in self.query_filter.children: + if isinstance(child, self.query_filter.__class__): + print 'SQ: ', child # TODO: Recursive call down tree... + else: + expression, value = child + field, filter_type = self.query_filter.split_expression(expression) + values.append(value) + + return xapian.Query(xapian.Query.OP_AND, values) + def run(self, spelling_query=None): """ Builds and executes the query. Returns a list of search results. From 60f4661ada627b64085baee14adfd6167a9e8f77 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Wed, 21 Oct 2009 16:20:17 -0400 Subject: [PATCH 20/98] More changes to build_query --- xapian_backend.py | 50 +++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 44 insertions(+), 6 deletions(-) diff --git a/xapian_backend.py b/xapian_backend.py index dc19d3e..b8b5ffe 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -934,11 +934,9 @@ class SearchQuery(BaseSearchQuery): self.backend = backend or SearchBackend() def build_query(self): - if not self.query_filter: - return xapian.Query('') - values = [] - + + return final_query for child in self.query_filter.children: if isinstance(child, self.query_filter.__class__): print 'SQ: ', child # TODO: Recursive call down tree... @@ -946,9 +944,49 @@ class SearchQuery(BaseSearchQuery): expression, value = child field, filter_type = self.query_filter.split_expression(expression) values.append(value) - + return xapian.Query(xapian.Query.OP_AND, values) - + + def build_query_fragment(self, field, filter_type, value): + """ + Builds a search query fragment from a field, filter type and value. + Returns: + A query string fragment suitable for parsing by Xapian. + """ + result = '' + + if not isinstance(value, (list, tuple)): + # Convert whatever we find to what xapian wants. + value = self.backend._marshal_value(value) + + # Check to see if it's a phrase for an exact match. + if ' ' in value: + value = '"%s"' % value + + # 'content' is a special reserved word, much like 'pk' in + # Django's ORM layer. It indicates 'no special field'. + if field == 'content': + result = value + else: + filter_types = { + 'exact': '%s:%s', + 'gte': '%s:%s..*', + 'gt': 'NOT %s:..%s', + 'lte': '%s:..%s', + 'lt': 'NOT %s:%s..*', + 'startswith': '%s:%s*', + } + + if filter_type != 'in': + result = filter_types[filter_type] % (field, value) + else: + in_options = [] + for possible_value in value: + in_options.append('%s:%s' % (field, possible_value)) + result = '(%s)' % ' OR '.join(in_options) + + return result + def run(self, spelling_query=None): """ Builds and executes the query. Returns a list of search results. From 01ecd8ac17c38a49002c4d9367bd98456a02eb0a Mon Sep 17 00:00:00 2001 From: David Sauve Date: Tue, 27 Oct 2009 22:03:04 -0400 Subject: [PATCH 21/98] Work on refactoring. Eliminated a lot of useless code and started to implement build_query using xapian.Query --- xapian_backend.py | 175 +++++++++++++++------------------------------- 1 file changed, 57 insertions(+), 118 deletions(-) diff --git a/xapian_backend.py b/xapian_backend.py index b8b5ffe..111ad82 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -932,125 +932,64 @@ class SearchQuery(BaseSearchQuery): """ super(SearchQuery, self).__init__(backend=backend) self.backend = backend or SearchBackend() - + def build_query(self): - values = [] - - return final_query - for child in self.query_filter.children: - if isinstance(child, self.query_filter.__class__): - print 'SQ: ', child # TODO: Recursive call down tree... - else: - expression, value = child - field, filter_type = self.query_filter.split_expression(expression) - values.append(value) - - return xapian.Query(xapian.Query.OP_AND, values) - - def build_query_fragment(self, field, filter_type, value): - """ - Builds a search query fragment from a field, filter type and value. - Returns: - A query string fragment suitable for parsing by Xapian. - """ - result = '' - - if not isinstance(value, (list, tuple)): - # Convert whatever we find to what xapian wants. - value = self.backend._marshal_value(value) - - # Check to see if it's a phrase for an exact match. - if ' ' in value: - value = '"%s"' % value - - # 'content' is a special reserved word, much like 'pk' in - # Django's ORM layer. It indicates 'no special field'. - if field == 'content': - result = value + if not self.query_filter.children: + return xapian.Query('') else: - filter_types = { - 'exact': '%s:%s', - 'gte': '%s:%s..*', - 'gt': 'NOT %s:..%s', - 'lte': '%s:..%s', - 'lt': 'NOT %s:%s..*', - 'startswith': '%s:%s*', - } + query_list = [] + + for child in self.query_filter.children: + if isinstance(child, self.query_filter.__class__): + pass + else: + expression, value = child + field, filter_type = self.query_filter.split_expression(expression) + query_list.append(xapian.Query(value)) + + return xapian.Query(xapian.Query.OP_AND, query_list) + - if filter_type != 'in': - result = filter_types[filter_type] % (field, value) - else: - in_options = [] - for possible_value in value: - in_options.append('%s:%s' % (field, possible_value)) - result = '(%s)' % ' OR '.join(in_options) - - return result - - def run(self, spelling_query=None): - """ - Builds and executes the query. Returns a list of search results. - - Returns: - List of search results - """ - final_query = self.build_query() - kwargs = { - 'start_offset': self.start_offset, - } - - if self.order_by: - kwargs['sort_by'] = self.order_by - - if self.end_offset is not None: - kwargs['end_offset'] = self.end_offset - self.start_offset - - if self.highlight: - kwargs['highlight'] = self.highlight - - if self.facets: - kwargs['facets'] = list(self.facets) - - if self.date_facets: - kwargs['date_facets'] = self.date_facets - - if self.query_facets: - kwargs['query_facets'] = self.query_facets - - if self.narrow_queries: - kwargs['narrow_queries'] = self.narrow_queries - - if spelling_query: - kwargs['spelling_query'] = spelling_query - - if self.boost: - kwargs['boost'] = self.boost - - results = self.backend.search(final_query, **kwargs) - self._results = results.get('results', []) - self._hit_count = results.get('hits', 0) - self._facet_counts = results.get('facets', {}) - self._spelling_suggestion = results.get('spelling_suggestion', None) + # def build_query_fragment(self, field, filter_type, value): + # print 'field: ', field + # print 'filter_type: ', filter_type + # print 'value: ', value - def run_mlt(self): - """ - Builds and executes the query. Returns a list of search results. - - Returns: - List of search results - """ - if self._more_like_this is False or self._mlt_instance is None: - raise MoreLikeThisError("No instance was provided to determine 'More Like This' results.") - - additional_query_string = self.build_query() - kwargs = { - 'start_offset': self.start_offset, - } - - if self.end_offset is not None: - kwargs['end_offset'] = self.end_offset - self.start_offset - - results = self.backend.more_like_this(self._mlt_instance, additional_query_string, **kwargs) - self._results = results.get('results', []) - self._hit_count = results.get('hits', 0) - + # """ + # Builds a search query fragment from a field, filter type and value. + # Returns: + # A query string fragment suitable for parsing by Xapian. + # """ + # result = '' + # + # if not isinstance(value, (list, tuple)): + # # Convert whatever we find to what xapian wants. + # value = self.backend._marshal_value(value) + # + # # Check to see if it's a phrase for an exact match. + # if ' ' in value: + # value = '"%s"' % value + # + # # 'content' is a special reserved word, much like 'pk' in + # # Django's ORM layer. It indicates 'no special field'. + # if field == 'content': + # result = value + # else: + # filter_types = { + # 'exact': '%s:%s', + # 'gte': '%s:%s..*', + # 'gt': 'NOT %s:..%s', + # 'lte': '%s:..%s', + # 'lt': 'NOT %s:%s..*', + # 'startswith': '%s:%s*', + # } + # + # if filter_type != 'in': + # result = filter_types[filter_type] % (field, value) + # else: + # in_options = [] + # for possible_value in value: + # in_options.append('%s:%s' % (field, possible_value)) + # result = '(%s)' % ' OR '.join(in_options) + # + # return result From 4242f77662abaa4759b35df0e9e690fe3eec5da5 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Mon, 9 Nov 2009 20:01:20 -0500 Subject: [PATCH 22/98] More refactor work --- tests/xapian_tests/tests/xapian_query.py | 22 +++++------ xapian_backend.py | 48 ++++++++++++++++-------- 2 files changed, 44 insertions(+), 26 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index 44d0862..d89eaa7 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -49,22 +49,22 @@ class XapianSearchQueryTestCase(TestCase): settings.HAYSTACK_XAPIAN_PATH = self.old_xapian_path super(XapianSearchQueryTestCase, self).tearDown() - def test_build_query_all(self): - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query()') + # def test_build_query_all(self): + # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query()') def test_build_query_single_word(self): self.sq.add_filter(SQ(content='hello')) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(hello)') - def test_build_query_multiple_words_and(self): - self.sq.add_filter(SQ(content='hello')) - self.sq.add_filter(SQ(content='world')) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND world))') - - def test_build_query_multiple_words_not(self): - self.sq.add_filter(~SQ(content='hello')) - self.sq.add_filter(~SQ(content='world')) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((NOT hello NOT world))') + # def test_build_query_multiple_words_and(self): + # self.sq.add_filter(SQ(content='hello')) + # self.sq.add_filter(SQ(content='world')) + # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND world))') + # + # def test_build_query_multiple_words_not(self): + # self.sq.add_filter(~SQ(content='hello')) + # self.sq.add_filter(~SQ(content='world')) + # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((NOT hello NOT world))') # def test_build_query_multiple_words_or(self): # self.sq.add_filter('content', 'hello', use_or=True) diff --git a/xapian_backend.py b/xapian_backend.py index 111ad82..ced5791 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -932,24 +932,42 @@ class SearchQuery(BaseSearchQuery): """ super(SearchQuery, self).__init__(backend=backend) self.backend = backend or SearchBackend() + + def as_xapian_query(self, parent, query_fragment_callback): + query_list = [] + + for child in parent.children: + if hasattr(child, 'as_query_string'): + query_list.append(self.as_xapian_query(child, query_fragment_callback)) + else: + expression, value = child + field, filter_type = self.query_filter.split_expression(expression) + query_list.append(query_fragment_callback(field, filter_type, value)) + + return xapian.Query(xapian.Query.OP_AND, query_list) def build_query(self): - if not self.query_filter.children: - return xapian.Query('') - else: - query_list = [] - - for child in self.query_filter.children: - if isinstance(child, self.query_filter.__class__): - pass - else: - expression, value = child - field, filter_type = self.query_filter.split_expression(expression) - query_list.append(xapian.Query(value)) - - return xapian.Query(xapian.Query.OP_AND, query_list) - + query = self.as_xapian_query(self.query_filter, self.build_query_fragment) + def build_query_fragment(self, field, filter_type, value): + return xapian.Query(value) + + # + # if not self.query_filter.children: + # return xapian.Query('') + # else: + # query_list = [] + # + # for child in self.query_filter.children: + # if isinstance(child, self.query_filter.__class__): + # query_list.append(self.build_query(child)) + # else: + # expression, value = child + # field, filter_type = self.query_filter.split_expression(expression) + # query_list.append(xapian.Query(value)) + # + # return xapian.Query(xapian.Query.OP_AND, query_list) + # def build_query_fragment(self, field, filter_type, value): # print 'field: ', field # print 'filter_type: ', filter_type From 68f8135f6326586f96c9d5abbc8d8d71561a1072 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Tue, 10 Nov 2009 20:45:37 -0500 Subject: [PATCH 23/98] Passing first two tests... --- tests/xapian_tests/tests/xapian_query.py | 4 ++-- xapian_backend.py | 22 ++++++++-------------- 2 files changed, 10 insertions(+), 16 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index d89eaa7..b94b7f5 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -49,8 +49,8 @@ class XapianSearchQueryTestCase(TestCase): settings.HAYSTACK_XAPIAN_PATH = self.old_xapian_path super(XapianSearchQueryTestCase, self).tearDown() - # def test_build_query_all(self): - # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query()') + def test_build_query_all(self): + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query()') def test_build_query_single_word(self): self.sq.add_filter(SQ(content='hello')) diff --git a/xapian_backend.py b/xapian_backend.py index ced5791..8c86ac0 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -933,21 +933,15 @@ class SearchQuery(BaseSearchQuery): super(SearchQuery, self).__init__(backend=backend) self.backend = backend or SearchBackend() - def as_xapian_query(self, parent, query_fragment_callback): - query_list = [] - - for child in parent.children: - if hasattr(child, 'as_query_string'): - query_list.append(self.as_xapian_query(child, query_fragment_callback)) - else: - expression, value = child - field, filter_type = self.query_filter.split_expression(expression) - query_list.append(query_fragment_callback(field, filter_type, value)) - - return xapian.Query(xapian.Query.OP_AND, query_list) - def build_query(self): - query = self.as_xapian_query(self.query_filter, self.build_query_fragment) + if not self.query_filter: + query = xapian.Query('') + else: + for child in self.query_filter.children: + expression, value = child + query = xapian.Query(value) + + return query def build_query_fragment(self, field, filter_type, value): return xapian.Query(value) From cf97b77818f83b8bfb9228908f4240ce782893ff Mon Sep 17 00:00:00 2001 From: David Sauve Date: Tue, 10 Nov 2009 20:47:59 -0500 Subject: [PATCH 24/98] Passing three tests. Empty query, single content value, multi-content values --- tests/xapian_tests/tests/xapian_query.py | 10 +++++----- xapian_backend.py | 6 +++++- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index b94b7f5..a3a5cbd 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -56,11 +56,11 @@ class XapianSearchQueryTestCase(TestCase): self.sq.add_filter(SQ(content='hello')) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(hello)') - # def test_build_query_multiple_words_and(self): - # self.sq.add_filter(SQ(content='hello')) - # self.sq.add_filter(SQ(content='world')) - # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND world))') - # + def test_build_query_multiple_words_and(self): + self.sq.add_filter(SQ(content='hello')) + self.sq.add_filter(SQ(content='world')) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND world))') + # def test_build_query_multiple_words_not(self): # self.sq.add_filter(~SQ(content='hello')) # self.sq.add_filter(~SQ(content='world')) diff --git a/xapian_backend.py b/xapian_backend.py index 8c86ac0..1d16ac5 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -937,9 +937,13 @@ class SearchQuery(BaseSearchQuery): if not self.query_filter: query = xapian.Query('') else: + query_list = [] + for child in self.query_filter.children: expression, value = child - query = xapian.Query(value) + query_list.append(value) + + query = xapian.Query(xapian.Query.OP_AND, query_list) return query From 8bb10c02d3b678c7390d5ebdd977ca6bb3336089 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Tue, 10 Nov 2009 21:31:25 -0500 Subject: [PATCH 25/98] Four tests passing now. Recursively parsing the search nodes and negated on NOT as required. --- tests/xapian_tests/tests/xapian_query.py | 8 ++--- xapian_backend.py | 39 ++++++++++++++++-------- 2 files changed, 30 insertions(+), 17 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index a3a5cbd..0509f2d 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -61,10 +61,10 @@ class XapianSearchQueryTestCase(TestCase): self.sq.add_filter(SQ(content='world')) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND world))') - # def test_build_query_multiple_words_not(self): - # self.sq.add_filter(~SQ(content='hello')) - # self.sq.add_filter(~SQ(content='world')) - # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((NOT hello NOT world))') + def test_build_query_multiple_words_not(self): + self.sq.add_filter(~SQ(content='hello')) + self.sq.add_filter(~SQ(content='world')) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((( AND_NOT hello) AND ( AND_NOT world)))') # def test_build_query_multiple_words_or(self): # self.sq.add_filter('content', 'hello', use_or=True) diff --git a/xapian_backend.py b/xapian_backend.py index 1d16ac5..7379469 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -15,7 +15,7 @@ # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. __author__ = 'David Sauve' -__version__ = (1, 0, 0, 'beta') +__version__ = (2, 0, 0, 'alpha') import time import datetime @@ -30,7 +30,7 @@ from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.encoding import smart_unicode, force_unicode -from haystack.backends import BaseSearchBackend, BaseSearchQuery, log_query +from haystack.backends import BaseSearchBackend, BaseSearchQuery, SearchNode, log_query from haystack.exceptions import MissingDependency from haystack.fields import DateField, DateTimeField, IntegerField, FloatField, BooleanField, MultiValueField from haystack.models import SearchResult @@ -935,19 +935,32 @@ class SearchQuery(BaseSearchQuery): def build_query(self): if not self.query_filter: - query = xapian.Query('') + return xapian.Query('') else: - query_list = [] - - for child in self.query_filter.children: - expression, value = child - query_list.append(value) - - query = xapian.Query(xapian.Query.OP_AND, query_list) - - return query + return self._query_from_search_node(self.query_filter) - def build_query_fragment(self, field, filter_type, value): + def _query_from_search_node(self, search_node, is_not=False): + query_list = [] + + for child in search_node.children: + if isinstance(child, SearchNode): + query_list.append( + xapian.Query( + xapian.Query.OP_AND, + self._query_from_search_node(child, child.negated) + ) + ) + else: + expression, value = child + if is_not: + # DS_TODO: This can almost definitely be improved. + query_list.append(xapian.Query(xapian.Query.OP_AND_NOT, '', value)) + else: + query_list.append(xapian.Query(value)) + + return xapian.Query(xapian.Query.OP_AND, query_list) + + def build_sub_query(self, value): return xapian.Query(value) # From b07842db65b1d1b2fcd7124aaec7a40aa302e4fa Mon Sep 17 00:00:00 2001 From: David Sauve Date: Tue, 10 Nov 2009 21:45:49 -0500 Subject: [PATCH 26/98] Five tests. OR operator now working --- tests/xapian_tests/tests/xapian_query.py | 9 ++++----- xapian_backend.py | 9 +++++++-- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index 0509f2d..189881f 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -66,11 +66,10 @@ class XapianSearchQueryTestCase(TestCase): self.sq.add_filter(~SQ(content='world')) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((( AND_NOT hello) AND ( AND_NOT world)))') - # def test_build_query_multiple_words_or(self): - # self.sq.add_filter('content', 'hello', use_or=True) - # self.sq.add_filter('content', 'world', use_or=True) - # self.assertEqual(self.sq.build_query(), 'hello OR world') - # + def test_build_query_multiple_words_or(self): + self.sq.add_filter(SQ(content='hello') | SQ(content='world')) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello OR world))') + # def test_build_query_multiple_words_mixed(self): # self.sq.add_filter('content', 'why') # self.sq.add_filter('content', 'hello', use_or=True) diff --git a/xapian_backend.py b/xapian_backend.py index 7379469..442d7fa 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -947,7 +947,9 @@ class SearchQuery(BaseSearchQuery): query_list.append( xapian.Query( xapian.Query.OP_AND, - self._query_from_search_node(child, child.negated) + self._query_from_search_node( + child, child.negated + ) ) ) else: @@ -958,7 +960,10 @@ class SearchQuery(BaseSearchQuery): else: query_list.append(xapian.Query(value)) - return xapian.Query(xapian.Query.OP_AND, query_list) + if search_node.connector == 'OR': + return xapian.Query(xapian.Query.OP_OR, query_list) + else: + return xapian.Query(xapian.Query.OP_AND, query_list) def build_sub_query(self, value): return xapian.Query(value) From 40322d6a7c4e5339db474c5d9f99ca4b9281035b Mon Sep 17 00:00:00 2001 From: David Sauve Date: Tue, 10 Nov 2009 21:53:32 -0500 Subject: [PATCH 27/98] Six passing tests. Combining AND, OR, NOT works. --- tests/xapian_tests/tests/xapian_query.py | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index 189881f..1578829 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -70,12 +70,11 @@ class XapianSearchQueryTestCase(TestCase): self.sq.add_filter(SQ(content='hello') | SQ(content='world')) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello OR world))') - # def test_build_query_multiple_words_mixed(self): - # self.sq.add_filter('content', 'why') - # self.sq.add_filter('content', 'hello', use_or=True) - # self.sq.add_filter('content', 'world', use_not=True) - # self.assertEqual(self.sq.build_query(), 'why OR hello NOT world') - # + def test_build_query_multiple_words_mixed(self): + self.sq.add_filter(SQ(content='why') | SQ(content='hello')) + self.sq.add_filter(~SQ(content='world')) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(((why OR hello) AND ( AND_NOT world)))') + # def test_build_query_phrase(self): # self.sq.add_filter('content', 'hello world') # self.assertEqual(self.sq.build_query(), '"hello world"') From 44bb6c6f48076ebd4781d7bc75b9620583617a32 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Wed, 21 Oct 2009 08:41:27 -0400 Subject: [PATCH 28/98] Started work in refactor --- tests/xapian_tests/tests/__init__.py | 2 +- tests/xapian_tests/tests/xapian_query.py | 134 +++++++++++------------ xapian_backend.py | 52 +++------ 3 files changed, 82 insertions(+), 106 deletions(-) diff --git a/tests/xapian_tests/tests/__init__.py b/tests/xapian_tests/tests/__init__.py index 25b3a6f..5b721c7 100644 --- a/tests/xapian_tests/tests/__init__.py +++ b/tests/xapian_tests/tests/__init__.py @@ -18,4 +18,4 @@ import warnings warnings.simplefilter('ignore', Warning) from xapian_tests.tests.xapian_query import * -from xapian_tests.tests.xapian_backend import * +# from xapian_tests.tests.xapian_backend import * diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index ecd96ec..44d0862 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -50,78 +50,78 @@ class XapianSearchQueryTestCase(TestCase): super(XapianSearchQueryTestCase, self).tearDown() def test_build_query_all(self): - self.assertEqual(self.sq.build_query(), '*') - + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query()') + def test_build_query_single_word(self): self.sq.add_filter(SQ(content='hello')) - self.assertEqual(self.sq.build_query(), 'hello') - + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(hello)') + def test_build_query_multiple_words_and(self): self.sq.add_filter(SQ(content='hello')) self.sq.add_filter(SQ(content='world')) - self.assertEqual(self.sq.build_query(), '(hello AND world)') - + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND world))') + def test_build_query_multiple_words_not(self): self.sq.add_filter(~SQ(content='hello')) self.sq.add_filter(~SQ(content='world')) - self.assertEqual(self.sq.build_query(), '(NOT (hello) AND NOT (world))') - - def test_build_query_multiple_words_or(self): - self.sq.add_filter(SQ(content='hello'), use_or=True) - self.sq.add_filter(SQ(content='world'), use_or=True) - self.assertEqual(self.sq.build_query(), '(hello OR world)') - - def test_build_query_multiple_words_mixed(self): - self.sq.add_filter(SQ(content='why')) - self.sq.add_filter(SQ(content='hello'), use_or=True) - self.sq.add_filter(~SQ(content='world')) - self.assertEqual(self.sq.build_query(), '((why OR hello) AND NOT (world))') - - def test_build_query_phrase(self): - self.sq.add_filter(SQ(content='hello world')) - self.assertEqual(self.sq.build_query(), '"hello world"') - - def test_build_query_multiple_filter_types(self): - self.sq.add_filter(SQ(content='why')) - self.sq.add_filter(SQ(pub_date__lte=datetime.datetime(2009, 2, 10, 1, 59))) - self.sq.add_filter(SQ(author__gt='david')) - self.sq.add_filter(SQ(created__lt=datetime.datetime(2009, 2, 12, 12, 13))) - self.sq.add_filter(SQ(title__gte='B')) - self.sq.add_filter(SQ(id__in=[1, 2, 3])) - self.assertEqual(self.sq.build_query(), '(why AND pub_date:..20090210015900 AND NOT author:..david AND NOT created:20090212121300..* AND title:B..* AND (id:1 OR id:2 OR id:3))') - - def test_build_query_multiple_exclude_types(self): - self.sq.add_filter(~SQ(content='why')) - self.sq.add_filter(~SQ(pub_date__lte=datetime.datetime(2009, 2, 10, 1, 59))) - self.sq.add_filter(~SQ(author__gt='david')) - self.sq.add_filter(~SQ(created__lt=datetime.datetime(2009, 2, 12, 12, 13))) - self.sq.add_filter(~SQ(title__gte='B')) - self.sq.add_filter(~SQ(id__in=[1, 2, 3])) - self.assertEqual(self.sq.build_query(), '(NOT (why) AND NOT (pub_date:..20090210015900) AND NOT (NOT author:..david) AND NOT (NOT created:20090212121300..*) AND NOT (title:B..*) AND NOT ((id:1 OR id:2 OR id:3)))') - - def test_build_query_wildcard_filter_types(self): - self.sq.add_filter(SQ(content='why')) - self.sq.add_filter(SQ(title__startswith='haystack')) - self.assertEqual(self.sq.build_query(), '(why AND title:haystack*)') - - def test_clean(self): - self.assertEqual(self.sq.clean('hello world'), 'hello world') - self.assertEqual(self.sq.clean('hello AND world'), 'hello and world') - self.assertEqual(self.sq.clean('hello AND OR NOT + - && || ! ( ) { } [ ] ^ " ~ * ? : \ world'), 'hello and or not \\+ \\- \\&& \\|| \\! \\( \\) \\{ \\} \\[ \\] \\^ \\" \\~ \\* \\? \\: \\\\ world') - self.assertEqual(self.sq.clean('so please NOTe i am in a bAND and bORed'), 'so please NOTe i am in a bAND and bORed') - - def test_build_query_with_models(self): - self.sq.add_filter(SQ(content='hello')) - self.sq.add_model(MockModel) - self.assertEqual(self.sq.build_query(), u'(hello) AND (django_ct:core.mockmodel)') - - self.sq.add_model(AnotherMockModel) - self.assertEqual(self.sq.build_query(), u'(hello) AND (django_ct:core.anothermockmodel OR django_ct:core.mockmodel)') - - def test_build_query_with_datetime(self): - self.sq.add_filter(SQ(pub_date=datetime.datetime(2009, 5, 9, 16, 20))) - self.assertEqual(self.sq.build_query(), u'pub_date:20090509162000') - - def test_build_query_with_sequence_and_filter_not_in(self): - self.sq.add_filter(SQ(id__exact=[1, 2, 3])) - self.assertEqual(self.sq.build_query(), u'id:[1, 2, 3]') \ No newline at end of file + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((NOT hello NOT world))') + + # def test_build_query_multiple_words_or(self): + # self.sq.add_filter('content', 'hello', use_or=True) + # self.sq.add_filter('content', 'world', use_or=True) + # self.assertEqual(self.sq.build_query(), 'hello OR world') + # + # def test_build_query_multiple_words_mixed(self): + # self.sq.add_filter('content', 'why') + # self.sq.add_filter('content', 'hello', use_or=True) + # self.sq.add_filter('content', 'world', use_not=True) + # self.assertEqual(self.sq.build_query(), 'why OR hello NOT world') + # + # def test_build_query_phrase(self): + # self.sq.add_filter('content', 'hello world') + # self.assertEqual(self.sq.build_query(), '"hello world"') + # + # def test_build_query_multiple_filter_types(self): + # self.sq.add_filter('content', 'why') + # self.sq.add_filter('pub_date__lte', datetime.datetime(2009, 2, 10, 1, 59)) + # self.sq.add_filter('author__gt', 'david') + # self.sq.add_filter('created__lt', datetime.datetime(2009, 2, 12, 12, 13)) + # self.sq.add_filter('title__gte', 'B') + # self.sq.add_filter('id__in', [1, 2, 3]) + # self.assertEqual(self.sq.build_query(), 'why AND pub_date:..20090210015900 AND NOT author:..david AND NOT created:20090212121300..* AND title:B..* AND (id:1 OR id:2 OR id:3)') + # + # def test_build_query_multiple_exclude_types(self): + # self.sq.add_filter('content', 'why', use_not=True) + # self.sq.add_filter('pub_date__lte', datetime.datetime(2009, 2, 10, 1, 59), use_not=True) + # self.sq.add_filter('author__gt', 'david', use_not=True) + # self.sq.add_filter('created__lt', datetime.datetime(2009, 2, 12, 12, 13), use_not=True) + # self.sq.add_filter('title__gte', 'B', use_not=True) + # self.sq.add_filter('id__in', [1, 2, 3], use_not=True) + # self.assertEqual(self.sq.build_query(), 'NOT why AND NOT pub_date:..20090210015900 AND author:..david AND created:20090212121300..* AND NOT title:B..* AND NOT id:1 NOT id:2 NOT id:3') + # + # def test_build_query_wildcard_filter_types(self): + # self.sq.add_filter('content', 'why') + # self.sq.add_filter('title__startswith', 'haystack') + # self.assertEqual(self.sq.build_query(), 'why AND title:haystack*') + # + # def test_clean(self): + # self.assertEqual(self.sq.clean('hello world'), 'hello world') + # self.assertEqual(self.sq.clean('hello AND world'), 'hello and world') + # self.assertEqual(self.sq.clean('hello AND OR NOT + - && || ! ( ) { } [ ] ^ " ~ * ? : \ world'), 'hello and or not \\+ \\- \\&& \\|| \\! \\( \\) \\{ \\} \\[ \\] \\^ \\" \\~ \\* \\? \\: \\\\ world') + # self.assertEqual(self.sq.clean('so please NOTe i am in a bAND and bORed'), 'so please NOTe i am in a bAND and bORed') + # + # def test_build_query_with_models(self): + # self.sq.add_filter('content', 'hello') + # self.sq.add_model(MockModel) + # self.assertEqual(self.sq.build_query(), u'(hello) django_ct:core.mockmodel') + # + # self.sq.add_model(AnotherMockModel) + # self.assertEqual(self.sq.build_query(), u'(hello) django_ct:core.anothermockmodel django_ct:core.mockmodel') + # + # def test_build_query_with_datetime(self): + # self.sq.add_filter('pub_date', datetime.datetime(2009, 5, 9, 16, 20)) + # self.assertEqual(self.sq.build_query(), u'pub_date:20090509162000') + # + # def test_build_query_with_sequence_and_filter_not_in(self): + # self.sq.add_filter('id__exact', [1, 2, 3]) + # self.assertEqual(self.sq.build_query(), u'id:[1, 2, 3]') diff --git a/xapian_backend.py b/xapian_backend.py index 2f48b6e..dc19d3e 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -933,46 +933,22 @@ class SearchQuery(BaseSearchQuery): super(SearchQuery, self).__init__(backend=backend) self.backend = backend or SearchBackend() - def build_query_fragment(self, field, filter_type, value): - """ - Builds a search query fragment from a field, filter type and value. - Returns: - A query string fragment suitable for parsing by Xapian. - """ - result = '' + def build_query(self): + if not self.query_filter: + return xapian.Query('') - if not isinstance(value, (list, tuple)): - # Convert whatever we find to what xapian wants. - value = self.backend._marshal_value(value) - - # Check to see if it's a phrase for an exact match. - if ' ' in value: - value = '"%s"' % value - - # 'content' is a special reserved word, much like 'pk' in - # Django's ORM layer. It indicates 'no special field'. - if field == 'content': - result = value - else: - filter_types = { - 'exact': '%s:%s', - 'gte': '%s:%s..*', - 'gt': 'NOT %s:..%s', - 'lte': '%s:..%s', - 'lt': 'NOT %s:%s..*', - 'startswith': '%s:%s*', - } - - if filter_type != 'in': - result = filter_types[filter_type] % (field, value) - else: - in_options = [] - for possible_value in value: - in_options.append('%s:%s' % (field, possible_value)) - result = '(%s)' % ' OR '.join(in_options) - - return result + values = [] + for child in self.query_filter.children: + if isinstance(child, self.query_filter.__class__): + print 'SQ: ', child # TODO: Recursive call down tree... + else: + expression, value = child + field, filter_type = self.query_filter.split_expression(expression) + values.append(value) + + return xapian.Query(xapian.Query.OP_AND, values) + def run(self, spelling_query=None): """ Builds and executes the query. Returns a list of search results. From 30a8f8fc0cd25ae5a7b88d8e3779e90571051d35 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Wed, 21 Oct 2009 16:20:17 -0400 Subject: [PATCH 29/98] More changes to build_query --- xapian_backend.py | 50 +++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 44 insertions(+), 6 deletions(-) diff --git a/xapian_backend.py b/xapian_backend.py index dc19d3e..b8b5ffe 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -934,11 +934,9 @@ class SearchQuery(BaseSearchQuery): self.backend = backend or SearchBackend() def build_query(self): - if not self.query_filter: - return xapian.Query('') - values = [] - + + return final_query for child in self.query_filter.children: if isinstance(child, self.query_filter.__class__): print 'SQ: ', child # TODO: Recursive call down tree... @@ -946,9 +944,49 @@ class SearchQuery(BaseSearchQuery): expression, value = child field, filter_type = self.query_filter.split_expression(expression) values.append(value) - + return xapian.Query(xapian.Query.OP_AND, values) - + + def build_query_fragment(self, field, filter_type, value): + """ + Builds a search query fragment from a field, filter type and value. + Returns: + A query string fragment suitable for parsing by Xapian. + """ + result = '' + + if not isinstance(value, (list, tuple)): + # Convert whatever we find to what xapian wants. + value = self.backend._marshal_value(value) + + # Check to see if it's a phrase for an exact match. + if ' ' in value: + value = '"%s"' % value + + # 'content' is a special reserved word, much like 'pk' in + # Django's ORM layer. It indicates 'no special field'. + if field == 'content': + result = value + else: + filter_types = { + 'exact': '%s:%s', + 'gte': '%s:%s..*', + 'gt': 'NOT %s:..%s', + 'lte': '%s:..%s', + 'lt': 'NOT %s:%s..*', + 'startswith': '%s:%s*', + } + + if filter_type != 'in': + result = filter_types[filter_type] % (field, value) + else: + in_options = [] + for possible_value in value: + in_options.append('%s:%s' % (field, possible_value)) + result = '(%s)' % ' OR '.join(in_options) + + return result + def run(self, spelling_query=None): """ Builds and executes the query. Returns a list of search results. From 555b13a5dec33dd73ee48b8370bd128b1bc61a55 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Tue, 27 Oct 2009 22:03:04 -0400 Subject: [PATCH 30/98] Work on refactoring. Eliminated a lot of useless code and started to implement build_query using xapian.Query --- xapian_backend.py | 175 +++++++++++++++------------------------------- 1 file changed, 57 insertions(+), 118 deletions(-) diff --git a/xapian_backend.py b/xapian_backend.py index b8b5ffe..111ad82 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -932,125 +932,64 @@ class SearchQuery(BaseSearchQuery): """ super(SearchQuery, self).__init__(backend=backend) self.backend = backend or SearchBackend() - + def build_query(self): - values = [] - - return final_query - for child in self.query_filter.children: - if isinstance(child, self.query_filter.__class__): - print 'SQ: ', child # TODO: Recursive call down tree... - else: - expression, value = child - field, filter_type = self.query_filter.split_expression(expression) - values.append(value) - - return xapian.Query(xapian.Query.OP_AND, values) - - def build_query_fragment(self, field, filter_type, value): - """ - Builds a search query fragment from a field, filter type and value. - Returns: - A query string fragment suitable for parsing by Xapian. - """ - result = '' - - if not isinstance(value, (list, tuple)): - # Convert whatever we find to what xapian wants. - value = self.backend._marshal_value(value) - - # Check to see if it's a phrase for an exact match. - if ' ' in value: - value = '"%s"' % value - - # 'content' is a special reserved word, much like 'pk' in - # Django's ORM layer. It indicates 'no special field'. - if field == 'content': - result = value + if not self.query_filter.children: + return xapian.Query('') else: - filter_types = { - 'exact': '%s:%s', - 'gte': '%s:%s..*', - 'gt': 'NOT %s:..%s', - 'lte': '%s:..%s', - 'lt': 'NOT %s:%s..*', - 'startswith': '%s:%s*', - } + query_list = [] + + for child in self.query_filter.children: + if isinstance(child, self.query_filter.__class__): + pass + else: + expression, value = child + field, filter_type = self.query_filter.split_expression(expression) + query_list.append(xapian.Query(value)) + + return xapian.Query(xapian.Query.OP_AND, query_list) + - if filter_type != 'in': - result = filter_types[filter_type] % (field, value) - else: - in_options = [] - for possible_value in value: - in_options.append('%s:%s' % (field, possible_value)) - result = '(%s)' % ' OR '.join(in_options) - - return result - - def run(self, spelling_query=None): - """ - Builds and executes the query. Returns a list of search results. - - Returns: - List of search results - """ - final_query = self.build_query() - kwargs = { - 'start_offset': self.start_offset, - } - - if self.order_by: - kwargs['sort_by'] = self.order_by - - if self.end_offset is not None: - kwargs['end_offset'] = self.end_offset - self.start_offset - - if self.highlight: - kwargs['highlight'] = self.highlight - - if self.facets: - kwargs['facets'] = list(self.facets) - - if self.date_facets: - kwargs['date_facets'] = self.date_facets - - if self.query_facets: - kwargs['query_facets'] = self.query_facets - - if self.narrow_queries: - kwargs['narrow_queries'] = self.narrow_queries - - if spelling_query: - kwargs['spelling_query'] = spelling_query - - if self.boost: - kwargs['boost'] = self.boost - - results = self.backend.search(final_query, **kwargs) - self._results = results.get('results', []) - self._hit_count = results.get('hits', 0) - self._facet_counts = results.get('facets', {}) - self._spelling_suggestion = results.get('spelling_suggestion', None) + # def build_query_fragment(self, field, filter_type, value): + # print 'field: ', field + # print 'filter_type: ', filter_type + # print 'value: ', value - def run_mlt(self): - """ - Builds and executes the query. Returns a list of search results. - - Returns: - List of search results - """ - if self._more_like_this is False or self._mlt_instance is None: - raise MoreLikeThisError("No instance was provided to determine 'More Like This' results.") - - additional_query_string = self.build_query() - kwargs = { - 'start_offset': self.start_offset, - } - - if self.end_offset is not None: - kwargs['end_offset'] = self.end_offset - self.start_offset - - results = self.backend.more_like_this(self._mlt_instance, additional_query_string, **kwargs) - self._results = results.get('results', []) - self._hit_count = results.get('hits', 0) - + # """ + # Builds a search query fragment from a field, filter type and value. + # Returns: + # A query string fragment suitable for parsing by Xapian. + # """ + # result = '' + # + # if not isinstance(value, (list, tuple)): + # # Convert whatever we find to what xapian wants. + # value = self.backend._marshal_value(value) + # + # # Check to see if it's a phrase for an exact match. + # if ' ' in value: + # value = '"%s"' % value + # + # # 'content' is a special reserved word, much like 'pk' in + # # Django's ORM layer. It indicates 'no special field'. + # if field == 'content': + # result = value + # else: + # filter_types = { + # 'exact': '%s:%s', + # 'gte': '%s:%s..*', + # 'gt': 'NOT %s:..%s', + # 'lte': '%s:..%s', + # 'lt': 'NOT %s:%s..*', + # 'startswith': '%s:%s*', + # } + # + # if filter_type != 'in': + # result = filter_types[filter_type] % (field, value) + # else: + # in_options = [] + # for possible_value in value: + # in_options.append('%s:%s' % (field, possible_value)) + # result = '(%s)' % ' OR '.join(in_options) + # + # return result From 96f16cb4e64f5d298571eff1d8f55e40002c4fac Mon Sep 17 00:00:00 2001 From: David Sauve Date: Mon, 9 Nov 2009 20:01:20 -0500 Subject: [PATCH 31/98] More refactor work --- tests/xapian_tests/tests/xapian_query.py | 22 +++++------ xapian_backend.py | 48 ++++++++++++++++-------- 2 files changed, 44 insertions(+), 26 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index 44d0862..d89eaa7 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -49,22 +49,22 @@ class XapianSearchQueryTestCase(TestCase): settings.HAYSTACK_XAPIAN_PATH = self.old_xapian_path super(XapianSearchQueryTestCase, self).tearDown() - def test_build_query_all(self): - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query()') + # def test_build_query_all(self): + # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query()') def test_build_query_single_word(self): self.sq.add_filter(SQ(content='hello')) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(hello)') - def test_build_query_multiple_words_and(self): - self.sq.add_filter(SQ(content='hello')) - self.sq.add_filter(SQ(content='world')) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND world))') - - def test_build_query_multiple_words_not(self): - self.sq.add_filter(~SQ(content='hello')) - self.sq.add_filter(~SQ(content='world')) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((NOT hello NOT world))') + # def test_build_query_multiple_words_and(self): + # self.sq.add_filter(SQ(content='hello')) + # self.sq.add_filter(SQ(content='world')) + # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND world))') + # + # def test_build_query_multiple_words_not(self): + # self.sq.add_filter(~SQ(content='hello')) + # self.sq.add_filter(~SQ(content='world')) + # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((NOT hello NOT world))') # def test_build_query_multiple_words_or(self): # self.sq.add_filter('content', 'hello', use_or=True) diff --git a/xapian_backend.py b/xapian_backend.py index 111ad82..ced5791 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -932,24 +932,42 @@ class SearchQuery(BaseSearchQuery): """ super(SearchQuery, self).__init__(backend=backend) self.backend = backend or SearchBackend() + + def as_xapian_query(self, parent, query_fragment_callback): + query_list = [] + + for child in parent.children: + if hasattr(child, 'as_query_string'): + query_list.append(self.as_xapian_query(child, query_fragment_callback)) + else: + expression, value = child + field, filter_type = self.query_filter.split_expression(expression) + query_list.append(query_fragment_callback(field, filter_type, value)) + + return xapian.Query(xapian.Query.OP_AND, query_list) def build_query(self): - if not self.query_filter.children: - return xapian.Query('') - else: - query_list = [] - - for child in self.query_filter.children: - if isinstance(child, self.query_filter.__class__): - pass - else: - expression, value = child - field, filter_type = self.query_filter.split_expression(expression) - query_list.append(xapian.Query(value)) - - return xapian.Query(xapian.Query.OP_AND, query_list) - + query = self.as_xapian_query(self.query_filter, self.build_query_fragment) + def build_query_fragment(self, field, filter_type, value): + return xapian.Query(value) + + # + # if not self.query_filter.children: + # return xapian.Query('') + # else: + # query_list = [] + # + # for child in self.query_filter.children: + # if isinstance(child, self.query_filter.__class__): + # query_list.append(self.build_query(child)) + # else: + # expression, value = child + # field, filter_type = self.query_filter.split_expression(expression) + # query_list.append(xapian.Query(value)) + # + # return xapian.Query(xapian.Query.OP_AND, query_list) + # def build_query_fragment(self, field, filter_type, value): # print 'field: ', field # print 'filter_type: ', filter_type From ac11ba627bf635a93997b73aae126bd5cc950e0d Mon Sep 17 00:00:00 2001 From: David Sauve Date: Tue, 10 Nov 2009 20:45:37 -0500 Subject: [PATCH 32/98] Passing first two tests... --- tests/xapian_tests/tests/xapian_query.py | 4 ++-- xapian_backend.py | 22 ++++++++-------------- 2 files changed, 10 insertions(+), 16 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index d89eaa7..b94b7f5 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -49,8 +49,8 @@ class XapianSearchQueryTestCase(TestCase): settings.HAYSTACK_XAPIAN_PATH = self.old_xapian_path super(XapianSearchQueryTestCase, self).tearDown() - # def test_build_query_all(self): - # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query()') + def test_build_query_all(self): + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query()') def test_build_query_single_word(self): self.sq.add_filter(SQ(content='hello')) diff --git a/xapian_backend.py b/xapian_backend.py index ced5791..8c86ac0 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -933,21 +933,15 @@ class SearchQuery(BaseSearchQuery): super(SearchQuery, self).__init__(backend=backend) self.backend = backend or SearchBackend() - def as_xapian_query(self, parent, query_fragment_callback): - query_list = [] - - for child in parent.children: - if hasattr(child, 'as_query_string'): - query_list.append(self.as_xapian_query(child, query_fragment_callback)) - else: - expression, value = child - field, filter_type = self.query_filter.split_expression(expression) - query_list.append(query_fragment_callback(field, filter_type, value)) - - return xapian.Query(xapian.Query.OP_AND, query_list) - def build_query(self): - query = self.as_xapian_query(self.query_filter, self.build_query_fragment) + if not self.query_filter: + query = xapian.Query('') + else: + for child in self.query_filter.children: + expression, value = child + query = xapian.Query(value) + + return query def build_query_fragment(self, field, filter_type, value): return xapian.Query(value) From 5905909b7c4112431430ada57cf3b038598c875b Mon Sep 17 00:00:00 2001 From: David Sauve Date: Tue, 10 Nov 2009 20:47:59 -0500 Subject: [PATCH 33/98] Passing three tests. Empty query, single content value, multi-content values --- tests/xapian_tests/tests/xapian_query.py | 10 +++++----- xapian_backend.py | 6 +++++- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index b94b7f5..a3a5cbd 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -56,11 +56,11 @@ class XapianSearchQueryTestCase(TestCase): self.sq.add_filter(SQ(content='hello')) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(hello)') - # def test_build_query_multiple_words_and(self): - # self.sq.add_filter(SQ(content='hello')) - # self.sq.add_filter(SQ(content='world')) - # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND world))') - # + def test_build_query_multiple_words_and(self): + self.sq.add_filter(SQ(content='hello')) + self.sq.add_filter(SQ(content='world')) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND world))') + # def test_build_query_multiple_words_not(self): # self.sq.add_filter(~SQ(content='hello')) # self.sq.add_filter(~SQ(content='world')) diff --git a/xapian_backend.py b/xapian_backend.py index 8c86ac0..1d16ac5 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -937,9 +937,13 @@ class SearchQuery(BaseSearchQuery): if not self.query_filter: query = xapian.Query('') else: + query_list = [] + for child in self.query_filter.children: expression, value = child - query = xapian.Query(value) + query_list.append(value) + + query = xapian.Query(xapian.Query.OP_AND, query_list) return query From 84988c69f3ffeee68da73e29d8c59cbef06f182b Mon Sep 17 00:00:00 2001 From: David Sauve Date: Tue, 10 Nov 2009 21:31:25 -0500 Subject: [PATCH 34/98] Four tests passing now. Recursively parsing the search nodes and negated on NOT as required. --- tests/xapian_tests/tests/xapian_query.py | 8 ++--- xapian_backend.py | 39 ++++++++++++++++-------- 2 files changed, 30 insertions(+), 17 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index a3a5cbd..0509f2d 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -61,10 +61,10 @@ class XapianSearchQueryTestCase(TestCase): self.sq.add_filter(SQ(content='world')) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND world))') - # def test_build_query_multiple_words_not(self): - # self.sq.add_filter(~SQ(content='hello')) - # self.sq.add_filter(~SQ(content='world')) - # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((NOT hello NOT world))') + def test_build_query_multiple_words_not(self): + self.sq.add_filter(~SQ(content='hello')) + self.sq.add_filter(~SQ(content='world')) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((( AND_NOT hello) AND ( AND_NOT world)))') # def test_build_query_multiple_words_or(self): # self.sq.add_filter('content', 'hello', use_or=True) diff --git a/xapian_backend.py b/xapian_backend.py index 1d16ac5..7379469 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -15,7 +15,7 @@ # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. __author__ = 'David Sauve' -__version__ = (1, 0, 0, 'beta') +__version__ = (2, 0, 0, 'alpha') import time import datetime @@ -30,7 +30,7 @@ from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.encoding import smart_unicode, force_unicode -from haystack.backends import BaseSearchBackend, BaseSearchQuery, log_query +from haystack.backends import BaseSearchBackend, BaseSearchQuery, SearchNode, log_query from haystack.exceptions import MissingDependency from haystack.fields import DateField, DateTimeField, IntegerField, FloatField, BooleanField, MultiValueField from haystack.models import SearchResult @@ -935,19 +935,32 @@ class SearchQuery(BaseSearchQuery): def build_query(self): if not self.query_filter: - query = xapian.Query('') + return xapian.Query('') else: - query_list = [] - - for child in self.query_filter.children: - expression, value = child - query_list.append(value) - - query = xapian.Query(xapian.Query.OP_AND, query_list) - - return query + return self._query_from_search_node(self.query_filter) - def build_query_fragment(self, field, filter_type, value): + def _query_from_search_node(self, search_node, is_not=False): + query_list = [] + + for child in search_node.children: + if isinstance(child, SearchNode): + query_list.append( + xapian.Query( + xapian.Query.OP_AND, + self._query_from_search_node(child, child.negated) + ) + ) + else: + expression, value = child + if is_not: + # DS_TODO: This can almost definitely be improved. + query_list.append(xapian.Query(xapian.Query.OP_AND_NOT, '', value)) + else: + query_list.append(xapian.Query(value)) + + return xapian.Query(xapian.Query.OP_AND, query_list) + + def build_sub_query(self, value): return xapian.Query(value) # From a96ed9e216e9f4937d8865e89755f5dc2e181db5 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Tue, 10 Nov 2009 21:45:49 -0500 Subject: [PATCH 35/98] Five tests. OR operator now working --- tests/xapian_tests/tests/xapian_query.py | 9 ++++----- xapian_backend.py | 9 +++++++-- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index 0509f2d..189881f 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -66,11 +66,10 @@ class XapianSearchQueryTestCase(TestCase): self.sq.add_filter(~SQ(content='world')) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((( AND_NOT hello) AND ( AND_NOT world)))') - # def test_build_query_multiple_words_or(self): - # self.sq.add_filter('content', 'hello', use_or=True) - # self.sq.add_filter('content', 'world', use_or=True) - # self.assertEqual(self.sq.build_query(), 'hello OR world') - # + def test_build_query_multiple_words_or(self): + self.sq.add_filter(SQ(content='hello') | SQ(content='world')) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello OR world))') + # def test_build_query_multiple_words_mixed(self): # self.sq.add_filter('content', 'why') # self.sq.add_filter('content', 'hello', use_or=True) diff --git a/xapian_backend.py b/xapian_backend.py index 7379469..442d7fa 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -947,7 +947,9 @@ class SearchQuery(BaseSearchQuery): query_list.append( xapian.Query( xapian.Query.OP_AND, - self._query_from_search_node(child, child.negated) + self._query_from_search_node( + child, child.negated + ) ) ) else: @@ -958,7 +960,10 @@ class SearchQuery(BaseSearchQuery): else: query_list.append(xapian.Query(value)) - return xapian.Query(xapian.Query.OP_AND, query_list) + if search_node.connector == 'OR': + return xapian.Query(xapian.Query.OP_OR, query_list) + else: + return xapian.Query(xapian.Query.OP_AND, query_list) def build_sub_query(self, value): return xapian.Query(value) From c92e8c7c7b2c7b0667178445e6b49fdb222ce4bd Mon Sep 17 00:00:00 2001 From: David Sauve Date: Tue, 10 Nov 2009 21:53:32 -0500 Subject: [PATCH 36/98] Six passing tests. Combining AND, OR, NOT works. --- tests/xapian_tests/tests/xapian_query.py | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index 189881f..1578829 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -70,12 +70,11 @@ class XapianSearchQueryTestCase(TestCase): self.sq.add_filter(SQ(content='hello') | SQ(content='world')) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello OR world))') - # def test_build_query_multiple_words_mixed(self): - # self.sq.add_filter('content', 'why') - # self.sq.add_filter('content', 'hello', use_or=True) - # self.sq.add_filter('content', 'world', use_not=True) - # self.assertEqual(self.sq.build_query(), 'why OR hello NOT world') - # + def test_build_query_multiple_words_mixed(self): + self.sq.add_filter(SQ(content='why') | SQ(content='hello')) + self.sq.add_filter(~SQ(content='world')) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(((why OR hello) AND ( AND_NOT world)))') + # def test_build_query_phrase(self): # self.sq.add_filter('content', 'hello world') # self.assertEqual(self.sq.build_query(), '"hello world"') From c7744fee70b409b546f745d75681db1a8ab88d8a Mon Sep 17 00:00:00 2001 From: David Sauve Date: Wed, 21 Oct 2009 08:41:27 -0400 Subject: [PATCH 37/98] Started work in refactor --- tests/xapian_tests/tests/xapian_query.py | 22 +++--- xapian_backend.py | 99 +++++++++++++----------- 2 files changed, 64 insertions(+), 57 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index 1578829..44d0862 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -64,17 +64,19 @@ class XapianSearchQueryTestCase(TestCase): def test_build_query_multiple_words_not(self): self.sq.add_filter(~SQ(content='hello')) self.sq.add_filter(~SQ(content='world')) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((( AND_NOT hello) AND ( AND_NOT world)))') - - def test_build_query_multiple_words_or(self): - self.sq.add_filter(SQ(content='hello') | SQ(content='world')) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello OR world))') - - def test_build_query_multiple_words_mixed(self): - self.sq.add_filter(SQ(content='why') | SQ(content='hello')) - self.sq.add_filter(~SQ(content='world')) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(((why OR hello) AND ( AND_NOT world)))') + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((NOT hello NOT world))') + # def test_build_query_multiple_words_or(self): + # self.sq.add_filter('content', 'hello', use_or=True) + # self.sq.add_filter('content', 'world', use_or=True) + # self.assertEqual(self.sq.build_query(), 'hello OR world') + # + # def test_build_query_multiple_words_mixed(self): + # self.sq.add_filter('content', 'why') + # self.sq.add_filter('content', 'hello', use_or=True) + # self.sq.add_filter('content', 'world', use_not=True) + # self.assertEqual(self.sq.build_query(), 'why OR hello NOT world') + # # def test_build_query_phrase(self): # self.sq.add_filter('content', 'hello world') # self.assertEqual(self.sq.build_query(), '"hello world"') diff --git a/xapian_backend.py b/xapian_backend.py index 442d7fa..b35c0f3 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -936,58 +936,63 @@ class SearchQuery(BaseSearchQuery): def build_query(self): if not self.query_filter: return xapian.Query('') - else: - return self._query_from_search_node(self.query_filter) - def _query_from_search_node(self, search_node, is_not=False): - query_list = [] + values = [] - for child in search_node.children: - if isinstance(child, SearchNode): - query_list.append( - xapian.Query( - xapian.Query.OP_AND, - self._query_from_search_node( - child, child.negated - ) - ) - ) + for child in self.query_filter.children: + if isinstance(child, self.query_filter.__class__): + print 'SQ: ', child # TODO: Recursive call down tree... else: expression, value = child - if is_not: - # DS_TODO: This can almost definitely be improved. - query_list.append(xapian.Query(xapian.Query.OP_AND_NOT, '', value)) - else: - query_list.append(xapian.Query(value)) + field, filter_type = self.query_filter.split_expression(expression) + values.append(value) - if search_node.connector == 'OR': - return xapian.Query(xapian.Query.OP_OR, query_list) - else: - return xapian.Query(xapian.Query.OP_AND, query_list) - - def build_sub_query(self, value): - return xapian.Query(value) - - # - # if not self.query_filter.children: - # return xapian.Query('') - # else: - # query_list = [] - # - # for child in self.query_filter.children: - # if isinstance(child, self.query_filter.__class__): - # query_list.append(self.build_query(child)) - # else: - # expression, value = child - # field, filter_type = self.query_filter.split_expression(expression) - # query_list.append(xapian.Query(value)) - # - # return xapian.Query(xapian.Query.OP_AND, query_list) - - # def build_query_fragment(self, field, filter_type, value): - # print 'field: ', field - # print 'filter_type: ', filter_type - # print 'value: ', value + return xapian.Query(xapian.Query.OP_AND, values) + + def run(self, spelling_query=None): + """ + Builds and executes the query. Returns a list of search results. + + Returns: + List of search results + """ + final_query = self.build_query() + kwargs = { + 'start_offset': self.start_offset, + } + + if self.order_by: + kwargs['sort_by'] = self.order_by + + if self.end_offset is not None: + kwargs['end_offset'] = self.end_offset - self.start_offset + + if self.highlight: + kwargs['highlight'] = self.highlight + + if self.facets: + kwargs['facets'] = list(self.facets) + + if self.date_facets: + kwargs['date_facets'] = self.date_facets + + if self.query_facets: + kwargs['query_facets'] = self.query_facets + + if self.narrow_queries: + kwargs['narrow_queries'] = self.narrow_queries + + if spelling_query: + kwargs['spelling_query'] = spelling_query + + if self.boost: + kwargs['boost'] = self.boost + + results = self.backend.search(final_query, **kwargs) + self._results = results.get('results', []) + self._hit_count = results.get('hits', 0) + self._facet_counts = results.get('facets', {}) + self._spelling_suggestion = results.get('spelling_suggestion', None) # """ # Builds a search query fragment from a field, filter type and value. From 8cfde151ddcb01c10c398897074a8d30a62b2801 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Wed, 21 Oct 2009 16:20:17 -0400 Subject: [PATCH 38/98] More changes to build_query --- xapian_backend.py | 50 +++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 44 insertions(+), 6 deletions(-) diff --git a/xapian_backend.py b/xapian_backend.py index b35c0f3..e08cf6f 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -934,11 +934,9 @@ class SearchQuery(BaseSearchQuery): self.backend = backend or SearchBackend() def build_query(self): - if not self.query_filter: - return xapian.Query('') - values = [] - + + return final_query for child in self.query_filter.children: if isinstance(child, self.query_filter.__class__): print 'SQ: ', child # TODO: Recursive call down tree... @@ -946,9 +944,49 @@ class SearchQuery(BaseSearchQuery): expression, value = child field, filter_type = self.query_filter.split_expression(expression) values.append(value) - + return xapian.Query(xapian.Query.OP_AND, values) - + + def build_query_fragment(self, field, filter_type, value): + """ + Builds a search query fragment from a field, filter type and value. + Returns: + A query string fragment suitable for parsing by Xapian. + """ + result = '' + + if not isinstance(value, (list, tuple)): + # Convert whatever we find to what xapian wants. + value = self.backend._marshal_value(value) + + # Check to see if it's a phrase for an exact match. + if ' ' in value: + value = '"%s"' % value + + # 'content' is a special reserved word, much like 'pk' in + # Django's ORM layer. It indicates 'no special field'. + if field == 'content': + result = value + else: + filter_types = { + 'exact': '%s:%s', + 'gte': '%s:%s..*', + 'gt': 'NOT %s:..%s', + 'lte': '%s:..%s', + 'lt': 'NOT %s:%s..*', + 'startswith': '%s:%s*', + } + + if filter_type != 'in': + result = filter_types[filter_type] % (field, value) + else: + in_options = [] + for possible_value in value: + in_options.append('%s:%s' % (field, possible_value)) + result = '(%s)' % ' OR '.join(in_options) + + return result + def run(self, spelling_query=None): """ Builds and executes the query. Returns a list of search results. From df46eea2920071dc0b8076b4d2643f7fe084b864 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Tue, 27 Oct 2009 22:03:04 -0400 Subject: [PATCH 39/98] Work on refactoring. Eliminated a lot of useless code and started to implement build_query using xapian.Query --- xapian_backend.py | 115 ++++++++-------------------------------------- 1 file changed, 19 insertions(+), 96 deletions(-) diff --git a/xapian_backend.py b/xapian_backend.py index e08cf6f..54f1966 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -932,105 +932,28 @@ class SearchQuery(BaseSearchQuery): """ super(SearchQuery, self).__init__(backend=backend) self.backend = backend or SearchBackend() - + def build_query(self): - values = [] - - return final_query - for child in self.query_filter.children: - if isinstance(child, self.query_filter.__class__): - print 'SQ: ', child # TODO: Recursive call down tree... - else: - expression, value = child - field, filter_type = self.query_filter.split_expression(expression) - values.append(value) - - return xapian.Query(xapian.Query.OP_AND, values) - - def build_query_fragment(self, field, filter_type, value): - """ - Builds a search query fragment from a field, filter type and value. - Returns: - A query string fragment suitable for parsing by Xapian. - """ - result = '' - - if not isinstance(value, (list, tuple)): - # Convert whatever we find to what xapian wants. - value = self.backend._marshal_value(value) - - # Check to see if it's a phrase for an exact match. - if ' ' in value: - value = '"%s"' % value - - # 'content' is a special reserved word, much like 'pk' in - # Django's ORM layer. It indicates 'no special field'. - if field == 'content': - result = value + if not self.query_filter.children: + return xapian.Query('') else: - filter_types = { - 'exact': '%s:%s', - 'gte': '%s:%s..*', - 'gt': 'NOT %s:..%s', - 'lte': '%s:..%s', - 'lt': 'NOT %s:%s..*', - 'startswith': '%s:%s*', - } + query_list = [] + + for child in self.query_filter.children: + if isinstance(child, self.query_filter.__class__): + pass + else: + expression, value = child + field, filter_type = self.query_filter.split_expression(expression) + query_list.append(xapian.Query(value)) + + return xapian.Query(xapian.Query.OP_AND, query_list) + - if filter_type != 'in': - result = filter_types[filter_type] % (field, value) - else: - in_options = [] - for possible_value in value: - in_options.append('%s:%s' % (field, possible_value)) - result = '(%s)' % ' OR '.join(in_options) - - return result - - def run(self, spelling_query=None): - """ - Builds and executes the query. Returns a list of search results. - - Returns: - List of search results - """ - final_query = self.build_query() - kwargs = { - 'start_offset': self.start_offset, - } - - if self.order_by: - kwargs['sort_by'] = self.order_by - - if self.end_offset is not None: - kwargs['end_offset'] = self.end_offset - self.start_offset - - if self.highlight: - kwargs['highlight'] = self.highlight - - if self.facets: - kwargs['facets'] = list(self.facets) - - if self.date_facets: - kwargs['date_facets'] = self.date_facets - - if self.query_facets: - kwargs['query_facets'] = self.query_facets - - if self.narrow_queries: - kwargs['narrow_queries'] = self.narrow_queries - - if spelling_query: - kwargs['spelling_query'] = spelling_query - - if self.boost: - kwargs['boost'] = self.boost - - results = self.backend.search(final_query, **kwargs) - self._results = results.get('results', []) - self._hit_count = results.get('hits', 0) - self._facet_counts = results.get('facets', {}) - self._spelling_suggestion = results.get('spelling_suggestion', None) + # def build_query_fragment(self, field, filter_type, value): + # print 'field: ', field + # print 'filter_type: ', filter_type + # print 'value: ', value # """ # Builds a search query fragment from a field, filter type and value. From 9b3b6d0b0217385615f7dc6af3c0dc436f5f4a88 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Mon, 9 Nov 2009 20:01:20 -0500 Subject: [PATCH 40/98] More refactor work --- tests/xapian_tests/tests/xapian_query.py | 22 +++++------ xapian_backend.py | 48 ++++++++++++++++-------- 2 files changed, 44 insertions(+), 26 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index 44d0862..d89eaa7 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -49,22 +49,22 @@ class XapianSearchQueryTestCase(TestCase): settings.HAYSTACK_XAPIAN_PATH = self.old_xapian_path super(XapianSearchQueryTestCase, self).tearDown() - def test_build_query_all(self): - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query()') + # def test_build_query_all(self): + # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query()') def test_build_query_single_word(self): self.sq.add_filter(SQ(content='hello')) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(hello)') - def test_build_query_multiple_words_and(self): - self.sq.add_filter(SQ(content='hello')) - self.sq.add_filter(SQ(content='world')) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND world))') - - def test_build_query_multiple_words_not(self): - self.sq.add_filter(~SQ(content='hello')) - self.sq.add_filter(~SQ(content='world')) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((NOT hello NOT world))') + # def test_build_query_multiple_words_and(self): + # self.sq.add_filter(SQ(content='hello')) + # self.sq.add_filter(SQ(content='world')) + # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND world))') + # + # def test_build_query_multiple_words_not(self): + # self.sq.add_filter(~SQ(content='hello')) + # self.sq.add_filter(~SQ(content='world')) + # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((NOT hello NOT world))') # def test_build_query_multiple_words_or(self): # self.sq.add_filter('content', 'hello', use_or=True) diff --git a/xapian_backend.py b/xapian_backend.py index 54f1966..996b28a 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -932,24 +932,42 @@ class SearchQuery(BaseSearchQuery): """ super(SearchQuery, self).__init__(backend=backend) self.backend = backend or SearchBackend() + + def as_xapian_query(self, parent, query_fragment_callback): + query_list = [] + + for child in parent.children: + if hasattr(child, 'as_query_string'): + query_list.append(self.as_xapian_query(child, query_fragment_callback)) + else: + expression, value = child + field, filter_type = self.query_filter.split_expression(expression) + query_list.append(query_fragment_callback(field, filter_type, value)) + + return xapian.Query(xapian.Query.OP_AND, query_list) def build_query(self): - if not self.query_filter.children: - return xapian.Query('') - else: - query_list = [] - - for child in self.query_filter.children: - if isinstance(child, self.query_filter.__class__): - pass - else: - expression, value = child - field, filter_type = self.query_filter.split_expression(expression) - query_list.append(xapian.Query(value)) - - return xapian.Query(xapian.Query.OP_AND, query_list) - + query = self.as_xapian_query(self.query_filter, self.build_query_fragment) + def build_query_fragment(self, field, filter_type, value): + return xapian.Query(value) + + # + # if not self.query_filter.children: + # return xapian.Query('') + # else: + # query_list = [] + # + # for child in self.query_filter.children: + # if isinstance(child, self.query_filter.__class__): + # query_list.append(self.build_query(child)) + # else: + # expression, value = child + # field, filter_type = self.query_filter.split_expression(expression) + # query_list.append(xapian.Query(value)) + # + # return xapian.Query(xapian.Query.OP_AND, query_list) + # def build_query_fragment(self, field, filter_type, value): # print 'field: ', field # print 'filter_type: ', filter_type From ef70ade65a73375e86399d1e57f1c8f632e2f43f Mon Sep 17 00:00:00 2001 From: David Sauve Date: Tue, 10 Nov 2009 20:45:37 -0500 Subject: [PATCH 41/98] Passing first two tests... --- tests/xapian_tests/tests/xapian_query.py | 4 ++-- xapian_backend.py | 22 ++++++++-------------- 2 files changed, 10 insertions(+), 16 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index d89eaa7..b94b7f5 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -49,8 +49,8 @@ class XapianSearchQueryTestCase(TestCase): settings.HAYSTACK_XAPIAN_PATH = self.old_xapian_path super(XapianSearchQueryTestCase, self).tearDown() - # def test_build_query_all(self): - # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query()') + def test_build_query_all(self): + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query()') def test_build_query_single_word(self): self.sq.add_filter(SQ(content='hello')) diff --git a/xapian_backend.py b/xapian_backend.py index 996b28a..616d6b0 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -933,21 +933,15 @@ class SearchQuery(BaseSearchQuery): super(SearchQuery, self).__init__(backend=backend) self.backend = backend or SearchBackend() - def as_xapian_query(self, parent, query_fragment_callback): - query_list = [] - - for child in parent.children: - if hasattr(child, 'as_query_string'): - query_list.append(self.as_xapian_query(child, query_fragment_callback)) - else: - expression, value = child - field, filter_type = self.query_filter.split_expression(expression) - query_list.append(query_fragment_callback(field, filter_type, value)) - - return xapian.Query(xapian.Query.OP_AND, query_list) - def build_query(self): - query = self.as_xapian_query(self.query_filter, self.build_query_fragment) + if not self.query_filter: + query = xapian.Query('') + else: + for child in self.query_filter.children: + expression, value = child + query = xapian.Query(value) + + return query def build_query_fragment(self, field, filter_type, value): return xapian.Query(value) From 3280b89d73e3730a0bea00f1a1cc9a642183d1a9 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Tue, 10 Nov 2009 20:47:59 -0500 Subject: [PATCH 42/98] Passing three tests. Empty query, single content value, multi-content values --- tests/xapian_tests/tests/xapian_query.py | 10 +++++----- xapian_backend.py | 6 +++++- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index b94b7f5..a3a5cbd 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -56,11 +56,11 @@ class XapianSearchQueryTestCase(TestCase): self.sq.add_filter(SQ(content='hello')) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(hello)') - # def test_build_query_multiple_words_and(self): - # self.sq.add_filter(SQ(content='hello')) - # self.sq.add_filter(SQ(content='world')) - # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND world))') - # + def test_build_query_multiple_words_and(self): + self.sq.add_filter(SQ(content='hello')) + self.sq.add_filter(SQ(content='world')) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND world))') + # def test_build_query_multiple_words_not(self): # self.sq.add_filter(~SQ(content='hello')) # self.sq.add_filter(~SQ(content='world')) diff --git a/xapian_backend.py b/xapian_backend.py index 616d6b0..8dc6bb8 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -937,9 +937,13 @@ class SearchQuery(BaseSearchQuery): if not self.query_filter: query = xapian.Query('') else: + query_list = [] + for child in self.query_filter.children: expression, value = child - query = xapian.Query(value) + query_list.append(value) + + query = xapian.Query(xapian.Query.OP_AND, query_list) return query From 3c42660a47bfc0cb9f39896f8c539c8f6d6c1c2f Mon Sep 17 00:00:00 2001 From: David Sauve Date: Tue, 10 Nov 2009 21:31:25 -0500 Subject: [PATCH 43/98] Four tests passing now. Recursively parsing the search nodes and negated on NOT as required. --- tests/xapian_tests/tests/xapian_query.py | 8 +++--- xapian_backend.py | 35 ++++++++++++++++-------- 2 files changed, 28 insertions(+), 15 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index a3a5cbd..0509f2d 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -61,10 +61,10 @@ class XapianSearchQueryTestCase(TestCase): self.sq.add_filter(SQ(content='world')) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND world))') - # def test_build_query_multiple_words_not(self): - # self.sq.add_filter(~SQ(content='hello')) - # self.sq.add_filter(~SQ(content='world')) - # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((NOT hello NOT world))') + def test_build_query_multiple_words_not(self): + self.sq.add_filter(~SQ(content='hello')) + self.sq.add_filter(~SQ(content='world')) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((( AND_NOT hello) AND ( AND_NOT world)))') # def test_build_query_multiple_words_or(self): # self.sq.add_filter('content', 'hello', use_or=True) diff --git a/xapian_backend.py b/xapian_backend.py index 8dc6bb8..7379469 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -935,19 +935,32 @@ class SearchQuery(BaseSearchQuery): def build_query(self): if not self.query_filter: - query = xapian.Query('') + return xapian.Query('') else: - query_list = [] - - for child in self.query_filter.children: - expression, value = child - query_list.append(value) - - query = xapian.Query(xapian.Query.OP_AND, query_list) - - return query + return self._query_from_search_node(self.query_filter) - def build_query_fragment(self, field, filter_type, value): + def _query_from_search_node(self, search_node, is_not=False): + query_list = [] + + for child in search_node.children: + if isinstance(child, SearchNode): + query_list.append( + xapian.Query( + xapian.Query.OP_AND, + self._query_from_search_node(child, child.negated) + ) + ) + else: + expression, value = child + if is_not: + # DS_TODO: This can almost definitely be improved. + query_list.append(xapian.Query(xapian.Query.OP_AND_NOT, '', value)) + else: + query_list.append(xapian.Query(value)) + + return xapian.Query(xapian.Query.OP_AND, query_list) + + def build_sub_query(self, value): return xapian.Query(value) # From d7e606f0d533df777afbb7f43483dc43d971a7e0 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Tue, 10 Nov 2009 21:45:49 -0500 Subject: [PATCH 44/98] Five tests. OR operator now working --- tests/xapian_tests/tests/xapian_query.py | 9 ++++----- xapian_backend.py | 9 +++++++-- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index 0509f2d..189881f 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -66,11 +66,10 @@ class XapianSearchQueryTestCase(TestCase): self.sq.add_filter(~SQ(content='world')) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((( AND_NOT hello) AND ( AND_NOT world)))') - # def test_build_query_multiple_words_or(self): - # self.sq.add_filter('content', 'hello', use_or=True) - # self.sq.add_filter('content', 'world', use_or=True) - # self.assertEqual(self.sq.build_query(), 'hello OR world') - # + def test_build_query_multiple_words_or(self): + self.sq.add_filter(SQ(content='hello') | SQ(content='world')) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello OR world))') + # def test_build_query_multiple_words_mixed(self): # self.sq.add_filter('content', 'why') # self.sq.add_filter('content', 'hello', use_or=True) diff --git a/xapian_backend.py b/xapian_backend.py index 7379469..442d7fa 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -947,7 +947,9 @@ class SearchQuery(BaseSearchQuery): query_list.append( xapian.Query( xapian.Query.OP_AND, - self._query_from_search_node(child, child.negated) + self._query_from_search_node( + child, child.negated + ) ) ) else: @@ -958,7 +960,10 @@ class SearchQuery(BaseSearchQuery): else: query_list.append(xapian.Query(value)) - return xapian.Query(xapian.Query.OP_AND, query_list) + if search_node.connector == 'OR': + return xapian.Query(xapian.Query.OP_OR, query_list) + else: + return xapian.Query(xapian.Query.OP_AND, query_list) def build_sub_query(self, value): return xapian.Query(value) From d6a24ef33c404746254f6c8749c6da87b523b415 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Tue, 10 Nov 2009 21:53:32 -0500 Subject: [PATCH 45/98] Six passing tests. Combining AND, OR, NOT works. --- tests/xapian_tests/tests/xapian_query.py | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index 189881f..1578829 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -70,12 +70,11 @@ class XapianSearchQueryTestCase(TestCase): self.sq.add_filter(SQ(content='hello') | SQ(content='world')) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello OR world))') - # def test_build_query_multiple_words_mixed(self): - # self.sq.add_filter('content', 'why') - # self.sq.add_filter('content', 'hello', use_or=True) - # self.sq.add_filter('content', 'world', use_not=True) - # self.assertEqual(self.sq.build_query(), 'why OR hello NOT world') - # + def test_build_query_multiple_words_mixed(self): + self.sq.add_filter(SQ(content='why') | SQ(content='hello')) + self.sq.add_filter(~SQ(content='world')) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(((why OR hello) AND ( AND_NOT world)))') + # def test_build_query_phrase(self): # self.sq.add_filter('content', 'hello world') # self.assertEqual(self.sq.build_query(), '"hello world"') From 3334b94349f98c575485de94bdf3f1ae3f402a5f Mon Sep 17 00:00:00 2001 From: David Sauve Date: Wed, 21 Oct 2009 08:41:27 -0400 Subject: [PATCH 46/98] Started work in refactor --- tests/xapian_tests/tests/xapian_query.py | 22 +++--- xapian_backend.py | 99 +++++++++++++----------- 2 files changed, 64 insertions(+), 57 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index 1578829..44d0862 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -64,17 +64,19 @@ class XapianSearchQueryTestCase(TestCase): def test_build_query_multiple_words_not(self): self.sq.add_filter(~SQ(content='hello')) self.sq.add_filter(~SQ(content='world')) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((( AND_NOT hello) AND ( AND_NOT world)))') - - def test_build_query_multiple_words_or(self): - self.sq.add_filter(SQ(content='hello') | SQ(content='world')) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello OR world))') - - def test_build_query_multiple_words_mixed(self): - self.sq.add_filter(SQ(content='why') | SQ(content='hello')) - self.sq.add_filter(~SQ(content='world')) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(((why OR hello) AND ( AND_NOT world)))') + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((NOT hello NOT world))') + # def test_build_query_multiple_words_or(self): + # self.sq.add_filter('content', 'hello', use_or=True) + # self.sq.add_filter('content', 'world', use_or=True) + # self.assertEqual(self.sq.build_query(), 'hello OR world') + # + # def test_build_query_multiple_words_mixed(self): + # self.sq.add_filter('content', 'why') + # self.sq.add_filter('content', 'hello', use_or=True) + # self.sq.add_filter('content', 'world', use_not=True) + # self.assertEqual(self.sq.build_query(), 'why OR hello NOT world') + # # def test_build_query_phrase(self): # self.sq.add_filter('content', 'hello world') # self.assertEqual(self.sq.build_query(), '"hello world"') diff --git a/xapian_backend.py b/xapian_backend.py index 442d7fa..b35c0f3 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -936,58 +936,63 @@ class SearchQuery(BaseSearchQuery): def build_query(self): if not self.query_filter: return xapian.Query('') - else: - return self._query_from_search_node(self.query_filter) - def _query_from_search_node(self, search_node, is_not=False): - query_list = [] + values = [] - for child in search_node.children: - if isinstance(child, SearchNode): - query_list.append( - xapian.Query( - xapian.Query.OP_AND, - self._query_from_search_node( - child, child.negated - ) - ) - ) + for child in self.query_filter.children: + if isinstance(child, self.query_filter.__class__): + print 'SQ: ', child # TODO: Recursive call down tree... else: expression, value = child - if is_not: - # DS_TODO: This can almost definitely be improved. - query_list.append(xapian.Query(xapian.Query.OP_AND_NOT, '', value)) - else: - query_list.append(xapian.Query(value)) + field, filter_type = self.query_filter.split_expression(expression) + values.append(value) - if search_node.connector == 'OR': - return xapian.Query(xapian.Query.OP_OR, query_list) - else: - return xapian.Query(xapian.Query.OP_AND, query_list) - - def build_sub_query(self, value): - return xapian.Query(value) - - # - # if not self.query_filter.children: - # return xapian.Query('') - # else: - # query_list = [] - # - # for child in self.query_filter.children: - # if isinstance(child, self.query_filter.__class__): - # query_list.append(self.build_query(child)) - # else: - # expression, value = child - # field, filter_type = self.query_filter.split_expression(expression) - # query_list.append(xapian.Query(value)) - # - # return xapian.Query(xapian.Query.OP_AND, query_list) - - # def build_query_fragment(self, field, filter_type, value): - # print 'field: ', field - # print 'filter_type: ', filter_type - # print 'value: ', value + return xapian.Query(xapian.Query.OP_AND, values) + + def run(self, spelling_query=None): + """ + Builds and executes the query. Returns a list of search results. + + Returns: + List of search results + """ + final_query = self.build_query() + kwargs = { + 'start_offset': self.start_offset, + } + + if self.order_by: + kwargs['sort_by'] = self.order_by + + if self.end_offset is not None: + kwargs['end_offset'] = self.end_offset - self.start_offset + + if self.highlight: + kwargs['highlight'] = self.highlight + + if self.facets: + kwargs['facets'] = list(self.facets) + + if self.date_facets: + kwargs['date_facets'] = self.date_facets + + if self.query_facets: + kwargs['query_facets'] = self.query_facets + + if self.narrow_queries: + kwargs['narrow_queries'] = self.narrow_queries + + if spelling_query: + kwargs['spelling_query'] = spelling_query + + if self.boost: + kwargs['boost'] = self.boost + + results = self.backend.search(final_query, **kwargs) + self._results = results.get('results', []) + self._hit_count = results.get('hits', 0) + self._facet_counts = results.get('facets', {}) + self._spelling_suggestion = results.get('spelling_suggestion', None) # """ # Builds a search query fragment from a field, filter type and value. From 8c61cdc9c2ba9ae4a92e829bd657b5ebb5a1558a Mon Sep 17 00:00:00 2001 From: David Sauve Date: Wed, 21 Oct 2009 16:20:17 -0400 Subject: [PATCH 47/98] More changes to build_query --- xapian_backend.py | 50 +++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 44 insertions(+), 6 deletions(-) diff --git a/xapian_backend.py b/xapian_backend.py index b35c0f3..e08cf6f 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -934,11 +934,9 @@ class SearchQuery(BaseSearchQuery): self.backend = backend or SearchBackend() def build_query(self): - if not self.query_filter: - return xapian.Query('') - values = [] - + + return final_query for child in self.query_filter.children: if isinstance(child, self.query_filter.__class__): print 'SQ: ', child # TODO: Recursive call down tree... @@ -946,9 +944,49 @@ class SearchQuery(BaseSearchQuery): expression, value = child field, filter_type = self.query_filter.split_expression(expression) values.append(value) - + return xapian.Query(xapian.Query.OP_AND, values) - + + def build_query_fragment(self, field, filter_type, value): + """ + Builds a search query fragment from a field, filter type and value. + Returns: + A query string fragment suitable for parsing by Xapian. + """ + result = '' + + if not isinstance(value, (list, tuple)): + # Convert whatever we find to what xapian wants. + value = self.backend._marshal_value(value) + + # Check to see if it's a phrase for an exact match. + if ' ' in value: + value = '"%s"' % value + + # 'content' is a special reserved word, much like 'pk' in + # Django's ORM layer. It indicates 'no special field'. + if field == 'content': + result = value + else: + filter_types = { + 'exact': '%s:%s', + 'gte': '%s:%s..*', + 'gt': 'NOT %s:..%s', + 'lte': '%s:..%s', + 'lt': 'NOT %s:%s..*', + 'startswith': '%s:%s*', + } + + if filter_type != 'in': + result = filter_types[filter_type] % (field, value) + else: + in_options = [] + for possible_value in value: + in_options.append('%s:%s' % (field, possible_value)) + result = '(%s)' % ' OR '.join(in_options) + + return result + def run(self, spelling_query=None): """ Builds and executes the query. Returns a list of search results. From c89addc959b1247394f13afcbba0a739fec07961 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Tue, 27 Oct 2009 22:03:04 -0400 Subject: [PATCH 48/98] Work on refactoring. Eliminated a lot of useless code and started to implement build_query using xapian.Query --- xapian_backend.py | 115 ++++++++-------------------------------------- 1 file changed, 19 insertions(+), 96 deletions(-) diff --git a/xapian_backend.py b/xapian_backend.py index e08cf6f..54f1966 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -932,105 +932,28 @@ class SearchQuery(BaseSearchQuery): """ super(SearchQuery, self).__init__(backend=backend) self.backend = backend or SearchBackend() - + def build_query(self): - values = [] - - return final_query - for child in self.query_filter.children: - if isinstance(child, self.query_filter.__class__): - print 'SQ: ', child # TODO: Recursive call down tree... - else: - expression, value = child - field, filter_type = self.query_filter.split_expression(expression) - values.append(value) - - return xapian.Query(xapian.Query.OP_AND, values) - - def build_query_fragment(self, field, filter_type, value): - """ - Builds a search query fragment from a field, filter type and value. - Returns: - A query string fragment suitable for parsing by Xapian. - """ - result = '' - - if not isinstance(value, (list, tuple)): - # Convert whatever we find to what xapian wants. - value = self.backend._marshal_value(value) - - # Check to see if it's a phrase for an exact match. - if ' ' in value: - value = '"%s"' % value - - # 'content' is a special reserved word, much like 'pk' in - # Django's ORM layer. It indicates 'no special field'. - if field == 'content': - result = value + if not self.query_filter.children: + return xapian.Query('') else: - filter_types = { - 'exact': '%s:%s', - 'gte': '%s:%s..*', - 'gt': 'NOT %s:..%s', - 'lte': '%s:..%s', - 'lt': 'NOT %s:%s..*', - 'startswith': '%s:%s*', - } + query_list = [] + + for child in self.query_filter.children: + if isinstance(child, self.query_filter.__class__): + pass + else: + expression, value = child + field, filter_type = self.query_filter.split_expression(expression) + query_list.append(xapian.Query(value)) + + return xapian.Query(xapian.Query.OP_AND, query_list) + - if filter_type != 'in': - result = filter_types[filter_type] % (field, value) - else: - in_options = [] - for possible_value in value: - in_options.append('%s:%s' % (field, possible_value)) - result = '(%s)' % ' OR '.join(in_options) - - return result - - def run(self, spelling_query=None): - """ - Builds and executes the query. Returns a list of search results. - - Returns: - List of search results - """ - final_query = self.build_query() - kwargs = { - 'start_offset': self.start_offset, - } - - if self.order_by: - kwargs['sort_by'] = self.order_by - - if self.end_offset is not None: - kwargs['end_offset'] = self.end_offset - self.start_offset - - if self.highlight: - kwargs['highlight'] = self.highlight - - if self.facets: - kwargs['facets'] = list(self.facets) - - if self.date_facets: - kwargs['date_facets'] = self.date_facets - - if self.query_facets: - kwargs['query_facets'] = self.query_facets - - if self.narrow_queries: - kwargs['narrow_queries'] = self.narrow_queries - - if spelling_query: - kwargs['spelling_query'] = spelling_query - - if self.boost: - kwargs['boost'] = self.boost - - results = self.backend.search(final_query, **kwargs) - self._results = results.get('results', []) - self._hit_count = results.get('hits', 0) - self._facet_counts = results.get('facets', {}) - self._spelling_suggestion = results.get('spelling_suggestion', None) + # def build_query_fragment(self, field, filter_type, value): + # print 'field: ', field + # print 'filter_type: ', filter_type + # print 'value: ', value # """ # Builds a search query fragment from a field, filter type and value. From 30bc0d0805d24a280a8281c618f3c5d0e4ee4855 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Mon, 9 Nov 2009 20:01:20 -0500 Subject: [PATCH 49/98] More refactor work --- tests/xapian_tests/tests/xapian_query.py | 22 +++++------ xapian_backend.py | 48 ++++++++++++++++-------- 2 files changed, 44 insertions(+), 26 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index 44d0862..d89eaa7 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -49,22 +49,22 @@ class XapianSearchQueryTestCase(TestCase): settings.HAYSTACK_XAPIAN_PATH = self.old_xapian_path super(XapianSearchQueryTestCase, self).tearDown() - def test_build_query_all(self): - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query()') + # def test_build_query_all(self): + # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query()') def test_build_query_single_word(self): self.sq.add_filter(SQ(content='hello')) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(hello)') - def test_build_query_multiple_words_and(self): - self.sq.add_filter(SQ(content='hello')) - self.sq.add_filter(SQ(content='world')) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND world))') - - def test_build_query_multiple_words_not(self): - self.sq.add_filter(~SQ(content='hello')) - self.sq.add_filter(~SQ(content='world')) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((NOT hello NOT world))') + # def test_build_query_multiple_words_and(self): + # self.sq.add_filter(SQ(content='hello')) + # self.sq.add_filter(SQ(content='world')) + # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND world))') + # + # def test_build_query_multiple_words_not(self): + # self.sq.add_filter(~SQ(content='hello')) + # self.sq.add_filter(~SQ(content='world')) + # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((NOT hello NOT world))') # def test_build_query_multiple_words_or(self): # self.sq.add_filter('content', 'hello', use_or=True) diff --git a/xapian_backend.py b/xapian_backend.py index 54f1966..996b28a 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -932,24 +932,42 @@ class SearchQuery(BaseSearchQuery): """ super(SearchQuery, self).__init__(backend=backend) self.backend = backend or SearchBackend() + + def as_xapian_query(self, parent, query_fragment_callback): + query_list = [] + + for child in parent.children: + if hasattr(child, 'as_query_string'): + query_list.append(self.as_xapian_query(child, query_fragment_callback)) + else: + expression, value = child + field, filter_type = self.query_filter.split_expression(expression) + query_list.append(query_fragment_callback(field, filter_type, value)) + + return xapian.Query(xapian.Query.OP_AND, query_list) def build_query(self): - if not self.query_filter.children: - return xapian.Query('') - else: - query_list = [] - - for child in self.query_filter.children: - if isinstance(child, self.query_filter.__class__): - pass - else: - expression, value = child - field, filter_type = self.query_filter.split_expression(expression) - query_list.append(xapian.Query(value)) - - return xapian.Query(xapian.Query.OP_AND, query_list) - + query = self.as_xapian_query(self.query_filter, self.build_query_fragment) + def build_query_fragment(self, field, filter_type, value): + return xapian.Query(value) + + # + # if not self.query_filter.children: + # return xapian.Query('') + # else: + # query_list = [] + # + # for child in self.query_filter.children: + # if isinstance(child, self.query_filter.__class__): + # query_list.append(self.build_query(child)) + # else: + # expression, value = child + # field, filter_type = self.query_filter.split_expression(expression) + # query_list.append(xapian.Query(value)) + # + # return xapian.Query(xapian.Query.OP_AND, query_list) + # def build_query_fragment(self, field, filter_type, value): # print 'field: ', field # print 'filter_type: ', filter_type From 529edc24b45b4286e528ce5b69d27269a3d3816e Mon Sep 17 00:00:00 2001 From: David Sauve Date: Tue, 10 Nov 2009 20:45:37 -0500 Subject: [PATCH 50/98] Passing first two tests... --- tests/xapian_tests/tests/xapian_query.py | 4 ++-- xapian_backend.py | 22 ++++++++-------------- 2 files changed, 10 insertions(+), 16 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index d89eaa7..b94b7f5 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -49,8 +49,8 @@ class XapianSearchQueryTestCase(TestCase): settings.HAYSTACK_XAPIAN_PATH = self.old_xapian_path super(XapianSearchQueryTestCase, self).tearDown() - # def test_build_query_all(self): - # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query()') + def test_build_query_all(self): + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query()') def test_build_query_single_word(self): self.sq.add_filter(SQ(content='hello')) diff --git a/xapian_backend.py b/xapian_backend.py index 996b28a..616d6b0 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -933,21 +933,15 @@ class SearchQuery(BaseSearchQuery): super(SearchQuery, self).__init__(backend=backend) self.backend = backend or SearchBackend() - def as_xapian_query(self, parent, query_fragment_callback): - query_list = [] - - for child in parent.children: - if hasattr(child, 'as_query_string'): - query_list.append(self.as_xapian_query(child, query_fragment_callback)) - else: - expression, value = child - field, filter_type = self.query_filter.split_expression(expression) - query_list.append(query_fragment_callback(field, filter_type, value)) - - return xapian.Query(xapian.Query.OP_AND, query_list) - def build_query(self): - query = self.as_xapian_query(self.query_filter, self.build_query_fragment) + if not self.query_filter: + query = xapian.Query('') + else: + for child in self.query_filter.children: + expression, value = child + query = xapian.Query(value) + + return query def build_query_fragment(self, field, filter_type, value): return xapian.Query(value) From 35f51e97bc173e1af92a4fda5aaebfca03232699 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Tue, 10 Nov 2009 20:47:59 -0500 Subject: [PATCH 51/98] Passing three tests. Empty query, single content value, multi-content values --- tests/xapian_tests/tests/xapian_query.py | 10 +++++----- xapian_backend.py | 6 +++++- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index b94b7f5..a3a5cbd 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -56,11 +56,11 @@ class XapianSearchQueryTestCase(TestCase): self.sq.add_filter(SQ(content='hello')) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(hello)') - # def test_build_query_multiple_words_and(self): - # self.sq.add_filter(SQ(content='hello')) - # self.sq.add_filter(SQ(content='world')) - # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND world))') - # + def test_build_query_multiple_words_and(self): + self.sq.add_filter(SQ(content='hello')) + self.sq.add_filter(SQ(content='world')) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND world))') + # def test_build_query_multiple_words_not(self): # self.sq.add_filter(~SQ(content='hello')) # self.sq.add_filter(~SQ(content='world')) diff --git a/xapian_backend.py b/xapian_backend.py index 616d6b0..8dc6bb8 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -937,9 +937,13 @@ class SearchQuery(BaseSearchQuery): if not self.query_filter: query = xapian.Query('') else: + query_list = [] + for child in self.query_filter.children: expression, value = child - query = xapian.Query(value) + query_list.append(value) + + query = xapian.Query(xapian.Query.OP_AND, query_list) return query From 09ffc6d481e4ba8abb2faae57a18d92f26f8b2a1 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Tue, 10 Nov 2009 21:31:25 -0500 Subject: [PATCH 52/98] Four tests passing now. Recursively parsing the search nodes and negated on NOT as required. --- tests/xapian_tests/tests/xapian_query.py | 8 +++--- xapian_backend.py | 35 ++++++++++++++++-------- 2 files changed, 28 insertions(+), 15 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index a3a5cbd..0509f2d 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -61,10 +61,10 @@ class XapianSearchQueryTestCase(TestCase): self.sq.add_filter(SQ(content='world')) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND world))') - # def test_build_query_multiple_words_not(self): - # self.sq.add_filter(~SQ(content='hello')) - # self.sq.add_filter(~SQ(content='world')) - # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((NOT hello NOT world))') + def test_build_query_multiple_words_not(self): + self.sq.add_filter(~SQ(content='hello')) + self.sq.add_filter(~SQ(content='world')) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((( AND_NOT hello) AND ( AND_NOT world)))') # def test_build_query_multiple_words_or(self): # self.sq.add_filter('content', 'hello', use_or=True) diff --git a/xapian_backend.py b/xapian_backend.py index 8dc6bb8..7379469 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -935,19 +935,32 @@ class SearchQuery(BaseSearchQuery): def build_query(self): if not self.query_filter: - query = xapian.Query('') + return xapian.Query('') else: - query_list = [] - - for child in self.query_filter.children: - expression, value = child - query_list.append(value) - - query = xapian.Query(xapian.Query.OP_AND, query_list) - - return query + return self._query_from_search_node(self.query_filter) - def build_query_fragment(self, field, filter_type, value): + def _query_from_search_node(self, search_node, is_not=False): + query_list = [] + + for child in search_node.children: + if isinstance(child, SearchNode): + query_list.append( + xapian.Query( + xapian.Query.OP_AND, + self._query_from_search_node(child, child.negated) + ) + ) + else: + expression, value = child + if is_not: + # DS_TODO: This can almost definitely be improved. + query_list.append(xapian.Query(xapian.Query.OP_AND_NOT, '', value)) + else: + query_list.append(xapian.Query(value)) + + return xapian.Query(xapian.Query.OP_AND, query_list) + + def build_sub_query(self, value): return xapian.Query(value) # From 537b1802a3ff72ffd5c9fea1552329c40fc1a62f Mon Sep 17 00:00:00 2001 From: David Sauve Date: Tue, 10 Nov 2009 21:45:49 -0500 Subject: [PATCH 53/98] Five tests. OR operator now working --- tests/xapian_tests/tests/xapian_query.py | 9 ++++----- xapian_backend.py | 9 +++++++-- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index 0509f2d..189881f 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -66,11 +66,10 @@ class XapianSearchQueryTestCase(TestCase): self.sq.add_filter(~SQ(content='world')) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((( AND_NOT hello) AND ( AND_NOT world)))') - # def test_build_query_multiple_words_or(self): - # self.sq.add_filter('content', 'hello', use_or=True) - # self.sq.add_filter('content', 'world', use_or=True) - # self.assertEqual(self.sq.build_query(), 'hello OR world') - # + def test_build_query_multiple_words_or(self): + self.sq.add_filter(SQ(content='hello') | SQ(content='world')) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello OR world))') + # def test_build_query_multiple_words_mixed(self): # self.sq.add_filter('content', 'why') # self.sq.add_filter('content', 'hello', use_or=True) diff --git a/xapian_backend.py b/xapian_backend.py index 7379469..442d7fa 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -947,7 +947,9 @@ class SearchQuery(BaseSearchQuery): query_list.append( xapian.Query( xapian.Query.OP_AND, - self._query_from_search_node(child, child.negated) + self._query_from_search_node( + child, child.negated + ) ) ) else: @@ -958,7 +960,10 @@ class SearchQuery(BaseSearchQuery): else: query_list.append(xapian.Query(value)) - return xapian.Query(xapian.Query.OP_AND, query_list) + if search_node.connector == 'OR': + return xapian.Query(xapian.Query.OP_OR, query_list) + else: + return xapian.Query(xapian.Query.OP_AND, query_list) def build_sub_query(self, value): return xapian.Query(value) From 91c58304f02f4281152b26c66da261425898b4ed Mon Sep 17 00:00:00 2001 From: David Sauve Date: Tue, 10 Nov 2009 21:53:32 -0500 Subject: [PATCH 54/98] Six passing tests. Combining AND, OR, NOT works. --- tests/xapian_tests/tests/xapian_query.py | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index 189881f..1578829 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -70,12 +70,11 @@ class XapianSearchQueryTestCase(TestCase): self.sq.add_filter(SQ(content='hello') | SQ(content='world')) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello OR world))') - # def test_build_query_multiple_words_mixed(self): - # self.sq.add_filter('content', 'why') - # self.sq.add_filter('content', 'hello', use_or=True) - # self.sq.add_filter('content', 'world', use_not=True) - # self.assertEqual(self.sq.build_query(), 'why OR hello NOT world') - # + def test_build_query_multiple_words_mixed(self): + self.sq.add_filter(SQ(content='why') | SQ(content='hello')) + self.sq.add_filter(~SQ(content='world')) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(((why OR hello) AND ( AND_NOT world)))') + # def test_build_query_phrase(self): # self.sq.add_filter('content', 'hello world') # self.assertEqual(self.sq.build_query(), '"hello world"') From b94eee10c5c5b358ae46cf0116051de99bc04cc7 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Fri, 13 Nov 2009 11:48:16 -0500 Subject: [PATCH 55/98] Remove unused build_sub_query method --- xapian_backend.py | 19 ------------------- 1 file changed, 19 deletions(-) diff --git a/xapian_backend.py b/xapian_backend.py index 442d7fa..2eafc87 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -965,25 +965,6 @@ class SearchQuery(BaseSearchQuery): else: return xapian.Query(xapian.Query.OP_AND, query_list) - def build_sub_query(self, value): - return xapian.Query(value) - - # - # if not self.query_filter.children: - # return xapian.Query('') - # else: - # query_list = [] - # - # for child in self.query_filter.children: - # if isinstance(child, self.query_filter.__class__): - # query_list.append(self.build_query(child)) - # else: - # expression, value = child - # field, filter_type = self.query_filter.split_expression(expression) - # query_list.append(xapian.Query(value)) - # - # return xapian.Query(xapian.Query.OP_AND, query_list) - # def build_query_fragment(self, field, filter_type, value): # print 'field: ', field # print 'filter_type: ', filter_type From 8987c532c66796f1a460197c02c68fcca088b1cd Mon Sep 17 00:00:00 2001 From: David Sauve Date: Thu, 19 Nov 2009 15:05:30 -0500 Subject: [PATCH 56/98] Cleaned up setUp an tearDown --- tests/xapian_tests/tests/xapian_query.py | 15 ++------------- 1 file changed, 2 insertions(+), 13 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index 1578829..76e3c99 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -16,6 +16,7 @@ import datetime import os +import shutil from django.conf import settings from django.test import TestCase @@ -29,24 +30,12 @@ from core.models import MockModel, AnotherMockModel class XapianSearchQueryTestCase(TestCase): def setUp(self): super(XapianSearchQueryTestCase, self).setUp() - - # Stow. - temp_path = os.path.join('tmp', 'test_xapian_query') - self.old_xapian_path = getattr(settings, 'HAYSTACK_XAPIAN_PATH', temp_path) - settings.HAYSTACK_XAPIAN_PATH = temp_path - self.sq = SearchQuery(backend=SearchBackend()) def tearDown(self): if os.path.exists(settings.HAYSTACK_XAPIAN_PATH): - index_files = os.listdir(settings.HAYSTACK_XAPIAN_PATH) + shutil.rmtree(settings.HAYSTACK_XAPIAN_PATH) - for index_file in index_files: - os.remove(os.path.join(settings.HAYSTACK_XAPIAN_PATH, index_file)) - - os.removedirs(settings.HAYSTACK_XAPIAN_PATH) - - settings.HAYSTACK_XAPIAN_PATH = self.old_xapian_path super(XapianSearchQueryTestCase, self).tearDown() def test_build_query_all(self): From bff2a62f93c31ec28631fe49a743489592ff7fbe Mon Sep 17 00:00:00 2001 From: David Sauve Date: Thu, 19 Nov 2009 15:06:12 -0500 Subject: [PATCH 57/98] Small cleanup of unused cruft in SearchQuery --- xapian_backend.py | 52 ++++------------------------------------------- 1 file changed, 4 insertions(+), 48 deletions(-) diff --git a/xapian_backend.py b/xapian_backend.py index 2eafc87..24d5432 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -256,7 +256,7 @@ class SearchBackend(BaseSearchBackend): """ database = self._database(writable=True) if not models: - query, __unused__ = self._query(database, '*') + query = xapian.Query('') enquire = self._enquire(database, query) for match in enquire.get_mset(0, DEFAULT_MAX_RESULTS): database.delete_document(match.docid) @@ -267,7 +267,7 @@ class SearchBackend(BaseSearchBackend): (model._meta.app_label, model._meta.module_name) ) @log_query - def search(self, query_string, sort_by=None, start_offset=0, + def search(self, query, sort_by=None, start_offset=0, end_offset=DEFAULT_MAX_RESULTS, fields='', highlight=False, facets=None, date_facets=None, query_facets=None, narrow_queries=None, boost=None, spelling_query=None, @@ -276,7 +276,7 @@ class SearchBackend(BaseSearchBackend): Executes the search as defined in `query_string`. Required arguments: - `query_string` -- Search query to execute + `query` -- Search query to execute Optional arguments: `sort_by` -- Sort results by specified field (default = None) @@ -319,7 +319,7 @@ class SearchBackend(BaseSearchBackend): and any suggestions for spell correction will be returned as well as the results. """ - if not query_string: + if not query: return { 'results': [], 'hits': 0, @@ -964,47 +964,3 @@ class SearchQuery(BaseSearchQuery): return xapian.Query(xapian.Query.OP_OR, query_list) else: return xapian.Query(xapian.Query.OP_AND, query_list) - - # def build_query_fragment(self, field, filter_type, value): - # print 'field: ', field - # print 'filter_type: ', filter_type - # print 'value: ', value - - # """ - # Builds a search query fragment from a field, filter type and value. - # Returns: - # A query string fragment suitable for parsing by Xapian. - # """ - # result = '' - # - # if not isinstance(value, (list, tuple)): - # # Convert whatever we find to what xapian wants. - # value = self.backend._marshal_value(value) - # - # # Check to see if it's a phrase for an exact match. - # if ' ' in value: - # value = '"%s"' % value - # - # # 'content' is a special reserved word, much like 'pk' in - # # Django's ORM layer. It indicates 'no special field'. - # if field == 'content': - # result = value - # else: - # filter_types = { - # 'exact': '%s:%s', - # 'gte': '%s:%s..*', - # 'gt': 'NOT %s:..%s', - # 'lte': '%s:..%s', - # 'lt': 'NOT %s:%s..*', - # 'startswith': '%s:%s*', - # } - # - # if filter_type != 'in': - # result = filter_types[filter_type] % (field, value) - # else: - # in_options = [] - # for possible_value in value: - # in_options.append('%s:%s' % (field, possible_value)) - # result = '(%s)' % ' OR '.join(in_options) - # - # return result From 500664a2e48b954fcedf6292b172580b59ebf304 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Sat, 28 Nov 2009 12:31:03 -0500 Subject: [PATCH 58/98] Merged master changes into next --- tests/xapian_tests/tests/xapian_backend.py | 21 +++++----- xapian_backend.py | 46 ++++++++++++---------- 2 files changed, 37 insertions(+), 30 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_backend.py b/tests/xapian_tests/tests/xapian_backend.py index 80fa3e1..ffbfdee 100644 --- a/tests/xapian_tests/tests/xapian_backend.py +++ b/tests/xapian_tests/tests/xapian_backend.py @@ -26,7 +26,7 @@ from django.utils.encoding import force_unicode from django.test import TestCase from haystack import indexes, sites -from haystack.backends.xapian_backend import SearchBackend, DEFAULT_MAX_RESULTS +from haystack.backends.xapian_backend import SearchBackend from core.models import MockTag, AnotherMockModel @@ -78,10 +78,6 @@ class XapianSearchBackendTestCase(TestCase): def setUp(self): super(XapianSearchBackendTestCase, self).setUp() - temp_path = os.path.join('tmp', 'test_xapian_query') - self.old_xapian_path = getattr(settings, 'HAYSTACK_XAPIAN_PATH', temp_path) - settings.HAYSTACK_XAPIAN_PATH = temp_path - self.site = XapianSearchSite() self.sb = SearchBackend(site=self.site) self.msi = XapianMockSearchIndex(XapianMockModel, backend=self.sb) @@ -100,14 +96,13 @@ class XapianSearchBackendTestCase(TestCase): self.sample_objs.append(mock) self.sample_objs[0].popularity = 834.0 - self.sample_objs[1].popularity = 35.0 + self.sample_objs[1].popularity = 35.5 self.sample_objs[2].popularity = 972.0 def tearDown(self): if os.path.exists(settings.HAYSTACK_XAPIAN_PATH): shutil.rmtree(settings.HAYSTACK_XAPIAN_PATH) - settings.HAYSTACK_XAPIAN_PATH = self.old_xapian_path super(XapianSearchBackendTestCase, self).tearDown() def xapian_search(self, query_string): @@ -120,7 +115,7 @@ class XapianSearchBackendTestCase(TestCase): query = xapian.Query(query_string) # Empty query matches all enquire = xapian.Enquire(database) enquire.set_query(query) - matches = enquire.get_mset(0, DEFAULT_MAX_RESULTS) + matches = enquire.get_mset(0, database.get_doccount()) document_list = [] @@ -189,6 +184,12 @@ class XapianSearchBackendTestCase(TestCase): self.assertEqual(self.sb.search('*')['hits'], 3) self.assertEqual([result.pk for result in self.sb.search('*')['results']], [1, 2, 3]) + # Exact match + self.assertEqual([result.pk for result in self.sb.search('name:david2')['results']], [2]) + self.assertEqual([result.pk for result in self.sb.search('value:10')['results']], [2]) + self.assertEqual([result.pk for result in self.sb.search('flag:false')['results']], [2]) + self.assertEqual([result.pk for result in self.sb.search('popularity:35.5')['results']], [2]) + # NOT operator self.assertEqual([result.pk for result in self.sb.search('NOT name:david1')['results']], [2, 3]) self.assertEqual([result.pk for result in self.sb.search('NOT name:david1 AND index')['results']], [2, 3]) @@ -262,8 +263,8 @@ class XapianSearchBackendTestCase(TestCase): self.sb.update(self.msi, self.sample_objs) self.assertEqual(len(self.xapian_search('')), 3) - self.assertEqual(self.sb.search('', narrow_queries=['name:david1']), {'hits': 0, 'results': []}) - results = self.sb.search('index', narrow_queries=['name:david1']) + self.assertEqual(self.sb.search('', narrow_queries=set(['name:david1'])), {'hits': 0, 'results': []}) + results = self.sb.search('index', narrow_queries=set(['name:david1'])) self.assertEqual(results['hits'], 1) def test_highlight(self): diff --git a/xapian_backend.py b/xapian_backend.py index 24d5432..8c827a3 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -31,7 +31,7 @@ from django.core.exceptions import ImproperlyConfigured from django.utils.encoding import smart_unicode, force_unicode from haystack.backends import BaseSearchBackend, BaseSearchQuery, SearchNode, log_query -from haystack.exceptions import MissingDependency +from haystack.exceptions import MissingDependency, HaystackError from haystack.fields import DateField, DateTimeField, IntegerField, FloatField, BooleanField, MultiValueField from haystack.models import SearchResult from haystack.utils import get_identifier @@ -42,13 +42,16 @@ except ImportError: raise MissingDependency("The 'xapian' backend requires the installation of 'xapian'. Please refer to the documentation.") -DEFAULT_MAX_RESULTS = 100000 - DOCUMENT_ID_TERM_PREFIX = 'Q' DOCUMENT_CUSTOM_TERM_PREFIX = 'X' DOCUMENT_CT_TERM_PREFIX = DOCUMENT_CUSTOM_TERM_PREFIX + 'CONTENTTYPE' +class InvalidIndexError(HaystackError): + """Raised when an index can not be opened.""" + pass + + class XHValueRangeProcessor(xapian.ValueRangeProcessor): def __init__(self, sb): self.sb = sb @@ -258,7 +261,7 @@ class SearchBackend(BaseSearchBackend): if not models: query = xapian.Query('') enquire = self._enquire(database, query) - for match in enquire.get_mset(0, DEFAULT_MAX_RESULTS): + for match in enquire.get_mset(0, self.document_count()): database.delete_document(match.docid) else: for model in models: @@ -268,7 +271,7 @@ class SearchBackend(BaseSearchBackend): ) @log_query def search(self, query, sort_by=None, start_offset=0, - end_offset=DEFAULT_MAX_RESULTS, fields='', highlight=False, + end_offset=0, fields='', highlight=False, facets=None, date_facets=None, query_facets=None, narrow_queries=None, boost=None, spelling_query=None, limit_to_registered_models=True, **kwargs): @@ -281,7 +284,7 @@ class SearchBackend(BaseSearchBackend): Optional arguments: `sort_by` -- Sort results by specified field (default = None) `start_offset` -- Slice results from `start_offset` (default = 0) - `end_offset` -- Slice results at `end_offset` (default = 10,000) + `end_offset` -- Slice results at `end_offset` (default = 0), if 0, then all documents `fields` -- Filter results on `fields` (default = '') `highlight` -- Highlight terms in results (default = False) `facets` -- Facet results on fields (default = None) @@ -327,12 +330,12 @@ class SearchBackend(BaseSearchBackend): if limit_to_registered_models: if narrow_queries is None: - narrow_queries = [] + narrow_queries = set() registered_models = self.build_registered_models_list() if len(registered_models) > 0: - narrow_queries.append( + narrow_queries.add( ' '.join(['django_ct:%s' % model for model in registered_models]) ) @@ -352,6 +355,8 @@ class SearchBackend(BaseSearchBackend): 'dates': {}, 'queries': {}, } + if not end_offset: + end_offset = self.document_count() matches = enquire.get_mset(start_offset, (end_offset - start_offset)) for match in matches: @@ -393,14 +398,10 @@ class SearchBackend(BaseSearchBackend): """ Retrieves the total document count for the search index. """ - try: - database = self._database() - except xapian.DatabaseOpeningError: - return 0 - return database.get_doccount() + return self._database().get_doccount() def more_like_this(self, model_instance, additional_query_string=None, - start_offset=0, end_offset=DEFAULT_MAX_RESULTS, + start_offset=0, end_offset=0, limit_to_registered_models=True, **kwargs): """ Given a model instance, returns a result set of similar documents. @@ -413,7 +414,7 @@ class SearchBackend(BaseSearchBackend): `additional_query_string` -- An additional query string to narrow results `start_offset` -- The starting offset (default=0) - `end_offset` -- The ending offset (default=None) + `end_offset` -- The ending offset (default=0), if 0, then all documents `limit_to_registered_models` -- Limit returned results to models registered in the current `SearchSite` (default = True) Returns: @@ -436,10 +437,12 @@ class SearchBackend(BaseSearchBackend): query = xapian.Query(DOCUMENT_ID_TERM_PREFIX + get_identifier(model_instance)) enquire = self._enquire(database, query) rset = xapian.RSet() - for match in enquire.get_mset(0, DEFAULT_MAX_RESULTS): + if not end_offset: + end_offset = self.document_count() + for match in enquire.get_mset(0, end_offset): rset.add_document(match.docid) query = xapian.Query(xapian.Query.OP_OR, - [expand.term for expand in enquire.get_eset(DEFAULT_MAX_RESULTS, rset, XHExpandDecider())] + [expand.term for expand in enquire.get_eset(match.document.termlist_count(), rset, XHExpandDecider())] ) query = xapian.Query( xapian.Query.OP_AND_NOT, [query, DOCUMENT_ID_TERM_PREFIX + get_identifier(model_instance)] @@ -449,8 +452,8 @@ class SearchBackend(BaseSearchBackend): registered_models = self.build_registered_models_list() if len(registered_models) > 0: - narrow_queries = [] - narrow_queries.append( + narrow_queries = set() + narrow_queries.add( ' '.join(['django_ct:%s' % model for model in registered_models]) ) if additional_query_string: @@ -720,7 +723,10 @@ class SearchBackend(BaseSearchBackend): database.set_metadata('schema', pickle.dumps(self.schema, pickle.HIGHEST_PROTOCOL)) database.set_metadata('content', pickle.dumps(self.content_field_name, pickle.HIGHEST_PROTOCOL)) else: - database = xapian.Database(settings.HAYSTACK_XAPIAN_PATH) + try: + database = xapian.Database(settings.HAYSTACK_XAPIAN_PATH) + except xapian.DatabaseOpeningError: + raise InvalidIndexError(u'Unable to open index at %s' % settings.HAYSTACK_XAPIAN_PATH) self.schema = pickle.loads(database.get_metadata('schema')) self.content_field_name = pickle.loads(database.get_metadata('content')) From 1ce5b2ca141d7db633892f6043a9a9f3f3e07d8c Mon Sep 17 00:00:00 2001 From: David Sauve Date: Sat, 28 Nov 2009 12:34:21 -0500 Subject: [PATCH 59/98] Merged more master changes into next --- tests/xapian_tests/tests/xapian_backend.py | 6 +++--- xapian_backend.py | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_backend.py b/tests/xapian_tests/tests/xapian_backend.py index ffbfdee..173d29e 100644 --- a/tests/xapian_tests/tests/xapian_backend.py +++ b/tests/xapian_tests/tests/xapian_backend.py @@ -136,7 +136,7 @@ class XapianSearchBackendTestCase(TestCase): self.assertEqual(len(self.xapian_search('')), 3) self.assertEqual([dict(doc) for doc in self.xapian_search('')], [ {'flag': u't', 'name': u'david1', 'text': u'Indexed!\n1', 'sites': u"['1', '2', '3']", 'pub_date': u'20090224000000', 'value': u'000000000005', 'id': u'tests.xapianmockmodel.1', 'slug': u'http://example.com/1', 'popularity': '\xca\x84', 'django_id': u'1', 'django_ct': u'tests.xapianmockmodel'}, - {'flag': u'f', 'name': u'david2', 'text': u'Indexed!\n2', 'sites': u"['2', '4', '6']", 'pub_date': u'20090223000000', 'value': u'000000000010', 'id': u'tests.xapianmockmodel.2', 'slug': u'http://example.com/2', 'popularity': '\xb4`', 'django_id': u'2', 'django_ct': u'tests.xapianmockmodel'}, + {'flag': u'f', 'name': u'david2', 'text': u'Indexed!\n2', 'sites': u"['2', '4', '6']", 'pub_date': u'20090223000000', 'value': u'000000000010', 'id': u'tests.xapianmockmodel.2', 'slug': u'http://e {'flag': u't', 'name': u'david3', 'text': u'Indexed!\n3', 'sites': u"['3', '6', '9']", 'pub_date': u'20090222000000', 'value': u'000000000015', 'id': u'tests.xapianmockmodel.3', 'slug': u'http://example.com/3', 'popularity': '\xcb\x98', 'django_id': u'3', 'django_ct': u'tests.xapianmockmodel'} ]) @@ -147,7 +147,7 @@ class XapianSearchBackendTestCase(TestCase): self.sb.remove(self.sample_objs[0]) self.assertEqual(len(self.xapian_search('')), 2) self.assertEqual([dict(doc) for doc in self.xapian_search('')], [ - {'flag': u'f', 'name': u'david2', 'text': u'Indexed!\n2', 'sites': u"['2', '4', '6']", 'pub_date': u'20090223000000', 'value': u'000000000010', 'id': u'tests.xapianmockmodel.2', 'slug': u'http://example.com/2', 'popularity': '\xb4`', 'django_id': u'2', 'django_ct': u'tests.xapianmockmodel'}, + {'flag': u'f', 'name': u'david2', 'text': u'Indexed!\n2', 'sites': u"['2', '4', '6']", 'pub_date': u'20090223000000', 'value': u'000000000010', 'id': u'tests.xapianmockmodel.2', 'slug': u'http://e {'flag': u't', 'name': u'david3', 'text': u'Indexed!\n3', 'sites': u"['3', '6', '9']", 'pub_date': u'20090222000000', 'value': u'000000000015', 'id': u'tests.xapianmockmodel.3', 'slug': u'http://example.com/3', 'popularity': '\xcb\x98', 'django_id': u'3', 'django_ct': u'tests.xapianmockmodel'} ]) @@ -319,7 +319,7 @@ class XapianSearchBackendTestCase(TestCase): self.assert_(self.sb.document_count() > 0) self.sb.delete_index() - self.assertEqual(self.sb.document_count(), 0) + self.assertRaises(InvalidIndexError, self.sb.document_count) def test_order_by(self): self.sb.update(self.msi, self.sample_objs) diff --git a/xapian_backend.py b/xapian_backend.py index 8c827a3..8bc35f8 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -259,7 +259,7 @@ class SearchBackend(BaseSearchBackend): """ database = self._database(writable=True) if not models: - query = xapian.Query('') + query, __unused__ = self._query(database, '*') enquire = self._enquire(database, query) for match in enquire.get_mset(0, self.document_count()): database.delete_document(match.docid) From e9f2064454967f5ac48dc37c6fdff668b0521c5c Mon Sep 17 00:00:00 2001 From: David Sauve Date: Sat, 28 Nov 2009 18:55:11 -0500 Subject: [PATCH 60/98] Added tests for boolean query and datetime query. Also added test for phrase query. --- AUTHORS | 4 +- tests/xapian_tests/tests/xapian_query.py | 19 +++++- xapian_backend.py | 73 ++++++++++++------------ 3 files changed, 57 insertions(+), 39 deletions(-) diff --git a/AUTHORS b/AUTHORS index b6c761f..c3be2e8 100644 --- a/AUTHORS +++ b/AUTHORS @@ -10,4 +10,6 @@ Thanks to: * Joshua Jonah for changes to highlighting logic to avoid reserved words. * Jannis Leidel for setting up the code base for pip, easy_install and PyPI. * Erik Aigner for the initial patch to get_identifier changes. - * wshallum for a patch that makes date facets compatible with Python 2.4 \ No newline at end of file + * wshallum for a patch that makes date facets compatible with Python 2.4 + * askfor for reporting issues with narrow_queries and float fields. + \ No newline at end of file diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index 76e3c99..ade3952 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -45,6 +45,14 @@ class XapianSearchQueryTestCase(TestCase): self.sq.add_filter(SQ(content='hello')) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(hello)') + def test_build_query_boolean(self): + self.sq.add_filter(SQ(content=True)) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(true)') + + def test_build_query_datetime(self): + self.sq.add_filter(SQ(content=datetime.datetime(2009, 5, 8, 11, 28))) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(20090508T112800Z)') + def test_build_query_multiple_words_and(self): self.sq.add_filter(SQ(content='hello')) self.sq.add_filter(SQ(content='world')) @@ -64,9 +72,14 @@ class XapianSearchQueryTestCase(TestCase): self.sq.add_filter(~SQ(content='world')) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(((why OR hello) AND ( AND_NOT world)))') - # def test_build_query_phrase(self): - # self.sq.add_filter('content', 'hello world') - # self.assertEqual(self.sq.build_query(), '"hello world"') + def test_build_query_phrase(self): + self.sq.add_filter(SQ(content='hello world')) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(hello world)') + + # def test_build_query_boost(self): + # self.sq.add_filter(SQ(content='hello')) + # self.sq.add_boost('world', 5) + # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(hello world)') # # def test_build_query_multiple_filter_types(self): # self.sq.add_filter('content', 'why') diff --git a/xapian_backend.py b/xapian_backend.py index 8bc35f8..fce13ab 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -92,11 +92,11 @@ class XHValueRangeProcessor(xapian.ValueRangeProcessor): elif field_dict['type'] == 'date' or field_dict['type'] == 'datetime': end = u'99990101000000' if field_dict['type'] == 'float': - begin = self.sb._marshal_value(float(begin)) - end = self.sb._marshal_value(float(end)) + begin = _marshal_value(float(begin)) + end = _marshal_value(float(end)) elif field_dict['type'] == 'long': - begin = self.sb._marshal_value(long(begin)) - end = self.sb._marshal_value(long(end)) + begin = _marshal_value(long(begin)) + end = _marshal_value(long(end)) return field_dict['column'], str(begin), str(end) @@ -215,7 +215,7 @@ class SearchBackend(BaseSearchBackend): value = data[field['field_name']] term_generator.index_text(force_unicode(value)) term_generator.index_text(force_unicode(value), 1, prefix) - document.add_value(field['column'], self._marshal_value(value)) + document.add_value(field['column'], _marshal_value(value)) document.set_data(pickle.dumps( (obj._meta.app_label, obj._meta.module_name, obj.pk, data), @@ -676,36 +676,6 @@ class SearchBackend(BaseSearchBackend): return facet_dict - def _marshal_value(self, value): - """ - Private method that converts Python values to a string for Xapian values. - """ - if isinstance(value, datetime.datetime): - if value.microsecond: - value = u'%04d%02d%02d%02d%02d%02d%06d' % ( - value.year, value.month, value.day, value.hour, - value.minute, value.second, value.microsecond - ) - else: - value = u'%04d%02d%02d%02d%02d%02d' % ( - value.year, value.month, value.day, value.hour, - value.minute, value.second - ) - elif isinstance(value, datetime.date): - value = u'%04d%02d%02d000000' % (value.year, value.month, value.day) - elif isinstance(value, bool): - if value: - value = u't' - else: - value = u'f' - elif isinstance(value, float): - value = xapian.sortable_serialise(value) - elif isinstance(value, (int, long)): - value = u'%012d' % value - else: - value = force_unicode(value) - return value - def _database(self, writable=False): """ Private method that returns a xapian.Database for use and sets up @@ -960,6 +930,7 @@ class SearchQuery(BaseSearchQuery): ) else: expression, value = child + value = _marshal_value(value) if is_not: # DS_TODO: This can almost definitely be improved. query_list.append(xapian.Query(xapian.Query.OP_AND_NOT, '', value)) @@ -970,3 +941,35 @@ class SearchQuery(BaseSearchQuery): return xapian.Query(xapian.Query.OP_OR, query_list) else: return xapian.Query(xapian.Query.OP_AND, query_list) + + +def _marshal_value(value): + """ + Private method that converts Python values to a string for Xapian values. + """ + if isinstance(value, datetime.datetime): + if value.microsecond: + value = u'%04d%02d%02dT%02d%02d%02d%06dZ' % ( + value.year, value.month, value.day, value.hour, + value.minute, value.second, value.microsecond + ) + else: + value = u'%04d%02d%02dT%02d%02d%02dZ' % ( + value.year, value.month, value.day, value.hour, + value.minute, value.second + ) + elif isinstance(value, datetime.date): + value = u'%04d%02d%02dT000000Z' % (value.year, value.month, value.day) + elif isinstance(value, bool): + if value: + value = u'true' + else: + value = u'false' + elif isinstance(value, float): + value = xapian.sortable_serialise(value) + elif isinstance(value, (int, long)): + value = u'%012d' % value + else: + value = force_unicode(value) + return value + From 3cacb54cf5a861dc1dd96b2a5c437f1f5de38782 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Sun, 29 Nov 2009 16:05:36 -0500 Subject: [PATCH 61/98] Added term boosting --- tests/xapian_tests/tests/xapian_query.py | 10 +++++----- xapian_backend.py | 17 +++++++++++++++-- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index ade3952..4bfde62 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -76,11 +76,11 @@ class XapianSearchQueryTestCase(TestCase): self.sq.add_filter(SQ(content='hello world')) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(hello world)') - # def test_build_query_boost(self): - # self.sq.add_filter(SQ(content='hello')) - # self.sq.add_boost('world', 5) - # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(hello world)') - # + def test_build_query_boost(self): + self.sq.add_filter(SQ(content='hello')) + self.sq.add_boost('world', 5) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello OR 5 * world))') + # def test_build_query_multiple_filter_types(self): # self.sq.add_filter('content', 'why') # self.sq.add_filter('pub_date__lte', datetime.datetime(2009, 2, 10, 1, 59)) diff --git a/xapian_backend.py b/xapian_backend.py index fce13ab..039568e 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -911,9 +911,22 @@ class SearchQuery(BaseSearchQuery): def build_query(self): if not self.query_filter: - return xapian.Query('') + query = xapian.Query('') else: - return self._query_from_search_node(self.query_filter) + query = self._query_from_search_node(self.query_filter) + + if self.boost: + subqueries = [ + xapian.Query( + xapian.Query.OP_SCALE_WEIGHT, xapian.Query(term), value + ) for term, value in self.boost.iteritems() + ] + query = xapian.Query( + xapian.Query.OP_OR, query, + xapian.Query(xapian.Query.OP_AND, subqueries) + ) + + return query def _query_from_search_node(self, search_node, is_not=False): query_list = [] From 7dd36f47d84824a0b38c69a8bc4ba1a7f7359ae7 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Sun, 29 Nov 2009 16:29:52 -0500 Subject: [PATCH 62/98] Removed RESERVED_WORDS and RESERVED_CHARACTERS --- tests/xapian_tests/tests/xapian_query.py | 63 +++++++++++------------- xapian_backend.py | 43 +++------------- 2 files changed, 36 insertions(+), 70 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index 4bfde62..5d5e211 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -82,46 +82,39 @@ class XapianSearchQueryTestCase(TestCase): self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello OR 5 * world))') # def test_build_query_multiple_filter_types(self): - # self.sq.add_filter('content', 'why') - # self.sq.add_filter('pub_date__lte', datetime.datetime(2009, 2, 10, 1, 59)) - # self.sq.add_filter('author__gt', 'david') - # self.sq.add_filter('created__lt', datetime.datetime(2009, 2, 12, 12, 13)) - # self.sq.add_filter('title__gte', 'B') - # self.sq.add_filter('id__in', [1, 2, 3]) - # self.assertEqual(self.sq.build_query(), 'why AND pub_date:..20090210015900 AND NOT author:..david AND NOT created:20090212121300..* AND title:B..* AND (id:1 OR id:2 OR id:3)') + # self.sq.add_filter(SQ(content='why')) + # self.sq.add_filter(SQ(pub_date__lte='2009-02-10 01:59:00')) + # self.sq.add_filter(SQ(author__gt='daniel')) + # self.sq.add_filter(SQ(created__lt='2009-02-12 12:13:00')) + # self.sq.add_filter(SQ(title__gte='B')) + # self.sq.add_filter(SQ(id__in=[1, 2, 3])) + # self.assertEqual(self.sq.build_query(), u'(why AND pub_date:[* TO "2009-02-10 01:59:00"] AND author:{daniel TO *} AND created:{* TO "2009-02-12 12:13:00"} AND title:[B TO *] AND (id:"1" OR id:"2" OR id:"3"))') # - # def test_build_query_multiple_exclude_types(self): - # self.sq.add_filter('content', 'why', use_not=True) - # self.sq.add_filter('pub_date__lte', datetime.datetime(2009, 2, 10, 1, 59), use_not=True) - # self.sq.add_filter('author__gt', 'david', use_not=True) - # self.sq.add_filter('created__lt', datetime.datetime(2009, 2, 12, 12, 13), use_not=True) - # self.sq.add_filter('title__gte', 'B', use_not=True) - # self.sq.add_filter('id__in', [1, 2, 3], use_not=True) - # self.assertEqual(self.sq.build_query(), 'NOT why AND NOT pub_date:..20090210015900 AND author:..david AND created:20090212121300..* AND NOT title:B..* AND NOT id:1 NOT id:2 NOT id:3') + # def test_build_query_in_filter_multiple_words(self): + # self.sq.add_filter(SQ(content='why')) + # self.sq.add_filter(SQ(title__in=["A Famous Paper", "An Infamous Article"])) + # self.assertEqual(self.sq.build_query(), u'(why AND (title:"A Famous Paper" OR title:"An Infamous Article"))') + # + # def test_build_query_in_filter_datetime(self): + # self.sq.add_filter(SQ(content='why')) + # self.sq.add_filter(SQ(pub_date__in=[datetime.datetime(2009, 7, 6, 1, 56, 21)])) + # self.assertEqual(self.sq.build_query(), u'(why AND (pub_date:"2009-07-06T01:56:21Z"))') # # def test_build_query_wildcard_filter_types(self): - # self.sq.add_filter('content', 'why') - # self.sq.add_filter('title__startswith', 'haystack') - # self.assertEqual(self.sq.build_query(), 'why AND title:haystack*') - # - # def test_clean(self): - # self.assertEqual(self.sq.clean('hello world'), 'hello world') - # self.assertEqual(self.sq.clean('hello AND world'), 'hello and world') - # self.assertEqual(self.sq.clean('hello AND OR NOT + - && || ! ( ) { } [ ] ^ " ~ * ? : \ world'), 'hello and or not \\+ \\- \\&& \\|| \\! \\( \\) \\{ \\} \\[ \\] \\^ \\" \\~ \\* \\? \\: \\\\ world') - # self.assertEqual(self.sq.clean('so please NOTe i am in a bAND and bORed'), 'so please NOTe i am in a bAND and bORed') + # self.sq.add_filter(SQ(content='why')) + # self.sq.add_filter(SQ(title__startswith='haystack')) + # self.assertEqual(self.sq.build_query(), u'(why AND title:haystack*)') # + def test_clean(self): + self.assertEqual(self.sq.clean('hello world'), 'hello world') + self.assertEqual(self.sq.clean('hello AND world'), 'hello AND world') + self.assertEqual(self.sq.clean('hello AND OR NOT TO + - && || ! ( ) { } [ ] ^ " ~ * ? : \ world'), 'hello AND OR NOT TO + - && || ! ( ) { } [ ] ^ " ~ * ? : \ world') + self.assertEqual(self.sq.clean('so please NOTe i am in a bAND and bORed'), 'so please NOTe i am in a bAND and bORed') + # def test_build_query_with_models(self): - # self.sq.add_filter('content', 'hello') + # self.sq.add_filter(SQ(content='hello')) # self.sq.add_model(MockModel) - # self.assertEqual(self.sq.build_query(), u'(hello) django_ct:core.mockmodel') + # self.assertEqual(self.sq.build_query(), '(hello) AND (django_ct:core.mockmodel)') # # self.sq.add_model(AnotherMockModel) - # self.assertEqual(self.sq.build_query(), u'(hello) django_ct:core.anothermockmodel django_ct:core.mockmodel') - # - # def test_build_query_with_datetime(self): - # self.sq.add_filter('pub_date', datetime.datetime(2009, 5, 9, 16, 20)) - # self.assertEqual(self.sq.build_query(), u'pub_date:20090509162000') - # - # def test_build_query_with_sequence_and_filter_not_in(self): - # self.sq.add_filter('id__exact', [1, 2, 3]) - # self.assertEqual(self.sq.build_query(), u'id:[1, 2, 3]') + # self.assertEqual(self.sq.build_query(), '(hello) AND (django_ct:core.mockmodel OR django_ct:core.anothermockmodel)') diff --git a/xapian_backend.py b/xapian_backend.py index 039568e..5acd502 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -130,20 +130,6 @@ class SearchBackend(BaseSearchBackend): your settings. This should point to a location where you would your indexes to reside. """ - RESERVED_WORDS = ( - 'AND', - 'NOT', - 'OR', - 'XOR', - 'NEAR', - 'ADJ', - ) - - RESERVED_CHARACTERS = ( - '\\', '+', '-', '&&', '||', '!', '(', ')', '{', '}', - '[', ']', '^', '"', '~', '*', '?', ':', - ) - def __init__(self, site=None, stemming_language='english'): """ Instantiates an instance of `SearchBackend`. @@ -270,10 +256,9 @@ class SearchBackend(BaseSearchBackend): (model._meta.app_label, model._meta.module_name) ) @log_query - def search(self, query, sort_by=None, start_offset=0, - end_offset=0, fields='', highlight=False, - facets=None, date_facets=None, query_facets=None, - narrow_queries=None, boost=None, spelling_query=None, + def search(self, query, sort_by=None, start_offset=0, end_offset=None, + fields='', highlight=False, facets=None, date_facets=None, + query_facets=None, narrow_queries=None, spelling_query=None, limit_to_registered_models=True, **kwargs): """ Executes the search as defined in `query_string`. @@ -284,7 +269,7 @@ class SearchBackend(BaseSearchBackend): Optional arguments: `sort_by` -- Sort results by specified field (default = None) `start_offset` -- Slice results from `start_offset` (default = 0) - `end_offset` -- Slice results at `end_offset` (default = 0), if 0, then all documents + `end_offset` -- Slice results at `end_offset` (default = None), if None, then all documents `fields` -- Filter results on `fields` (default = '') `highlight` -- Highlight terms in results (default = False) `facets` -- Facet results on fields (default = None) @@ -292,7 +277,6 @@ class SearchBackend(BaseSearchBackend): `query_facets` -- Facet results on queries (default = None) `narrow_queries` -- Narrow queries (default = None) `spelling_query` -- An optional query to execute spelling suggestion on - `boost` -- Dictionary of terms and weights to boost results `limit_to_registered_models` -- Limit returned results to models registered in the current `SearchSite` (default = True) Returns: @@ -341,7 +325,7 @@ class SearchBackend(BaseSearchBackend): database = self._database() query, spelling_suggestion = self._query( - database, query_string, narrow_queries, spelling_query, boost + database, query_string, narrow_queries, spelling_query ) enquire = self._enquire(database, query) @@ -401,7 +385,7 @@ class SearchBackend(BaseSearchBackend): return self._database().get_doccount() def more_like_this(self, model_instance, additional_query_string=None, - start_offset=0, end_offset=0, + start_offset=0, end_offset=None, limit_to_registered_models=True, **kwargs): """ Given a model instance, returns a result set of similar documents. @@ -414,7 +398,7 @@ class SearchBackend(BaseSearchBackend): `additional_query_string` -- An additional query string to narrow results `start_offset` -- The starting offset (default=0) - `end_offset` -- The ending offset (default=0), if 0, then all documents + `end_offset` -- The ending offset (default=None), if None, then all documents `limit_to_registered_models` -- Limit returned results to models registered in the current `SearchSite` (default = True) Returns: @@ -721,7 +705,7 @@ class SearchBackend(BaseSearchBackend): term_generator.set_document(document) return term_generator - def _query(self, database, query_string, narrow_queries=None, spelling_query=None, boost=None): + def _query(self, database, query_string, narrow_queries=None, spelling_query=None): """ Private method that takes a query string and returns a xapian.Query. @@ -732,7 +716,6 @@ class SearchBackend(BaseSearchBackend): Optional arguments: `narrow_queries` -- A list of queries to narrow the query with `spelling_query` -- An optional query to execute spelling suggestion on - `boost` -- A dictionary of terms to boost with values Returns a xapian.Query instance with prefixes and ranges properly setup as pulled from the `query_string`. @@ -766,16 +749,6 @@ class SearchBackend(BaseSearchBackend): xapian.Query.OP_FILTER, query, xapian.Query(xapian.Query.OP_AND, subqueries) ) - if boost: - subqueries = [ - xapian.Query( - xapian.Query.OP_SCALE_WEIGHT, xapian.Query(term), value - ) for term, value in boost.iteritems() - ] - query = xapian.Query( - xapian.Query.OP_OR, query, - xapian.Query(xapian.Query.OP_AND, subqueries) - ) return query, spelling_suggestion From 2a4b32f03b2b303f02b8913d8431aa2ab81911c4 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Sun, 29 Nov 2009 17:06:29 -0500 Subject: [PATCH 63/98] SearchQuery now supports model filtering --- tests/xapian_tests/tests/xapian_query.py | 14 +++++++------- xapian_backend.py | 13 +++++++++++++ 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index 5d5e211..d288f00 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -111,10 +111,10 @@ class XapianSearchQueryTestCase(TestCase): self.assertEqual(self.sq.clean('hello AND OR NOT TO + - && || ! ( ) { } [ ] ^ " ~ * ? : \ world'), 'hello AND OR NOT TO + - && || ! ( ) { } [ ] ^ " ~ * ? : \ world') self.assertEqual(self.sq.clean('so please NOTe i am in a bAND and bORed'), 'so please NOTe i am in a bAND and bORed') - # def test_build_query_with_models(self): - # self.sq.add_filter(SQ(content='hello')) - # self.sq.add_model(MockModel) - # self.assertEqual(self.sq.build_query(), '(hello) AND (django_ct:core.mockmodel)') - # - # self.sq.add_model(AnotherMockModel) - # self.assertEqual(self.sq.build_query(), '(hello) AND (django_ct:core.mockmodel OR django_ct:core.anothermockmodel)') + def test_build_query_with_models(self): + self.sq.add_filter(SQ(content='hello')) + self.sq.add_model(MockModel) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND XCONTENTTYPEcore.mockmodel))') + + self.sq.add_model(AnotherMockModel) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND (XCONTENTTYPEcore.anothermockmodel OR XCONTENTTYPEcore.mockmodel)))') diff --git a/xapian_backend.py b/xapian_backend.py index 5acd502..44ebdcc 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -888,6 +888,19 @@ class SearchQuery(BaseSearchQuery): else: query = self._query_from_search_node(self.query_filter) + if self.models: + subqueries = [ + xapian.Query('%s%s.%s' % ( + DOCUMENT_CT_TERM_PREFIX, + model._meta.app_label, model._meta.module_name + ) + ) for model in self.models + ] + query = xapian.Query( + xapian.Query.OP_AND, query, + xapian.Query(xapian.Query.OP_OR, subqueries) + ) + if self.boost: subqueries = [ xapian.Query( From 184f10af2d38fa577e640c11f3100a94e8657144 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Sun, 29 Nov 2009 19:12:59 -0500 Subject: [PATCH 64/98] Converted model filtering to use pure boolean subquery --- tests/xapian_tests/tests/xapian_query.py | 4 ++-- xapian_backend.py | 10 ++++++---- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index d288f00..58e9ea2 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -114,7 +114,7 @@ class XapianSearchQueryTestCase(TestCase): def test_build_query_with_models(self): self.sq.add_filter(SQ(content='hello')) self.sq.add_model(MockModel) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND XCONTENTTYPEcore.mockmodel))') + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND 0 * XCONTENTTYPEcore.mockmodel))') self.sq.add_model(AnotherMockModel) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND (XCONTENTTYPEcore.anothermockmodel OR XCONTENTTYPEcore.mockmodel)))') + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND (0 * XCONTENTTYPEcore.anothermockmodel OR 0 * XCONTENTTYPEcore.mockmodel)))') diff --git a/xapian_backend.py b/xapian_backend.py index 44ebdcc..a0a3ee2 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -890,10 +890,12 @@ class SearchQuery(BaseSearchQuery): if self.models: subqueries = [ - xapian.Query('%s%s.%s' % ( - DOCUMENT_CT_TERM_PREFIX, - model._meta.app_label, model._meta.module_name - ) + xapian.Query( + xapian.Query.OP_SCALE_WEIGHT, xapian.Query('%s%s.%s' % ( + DOCUMENT_CT_TERM_PREFIX, + model._meta.app_label, model._meta.module_name + ) + ), 0 ) for model in self.models ] query = xapian.Query( From 12a700877771455633b5cb96a2e29e89e918d23d Mon Sep 17 00:00:00 2001 From: David Sauve Date: Mon, 30 Nov 2009 06:26:34 -0500 Subject: [PATCH 65/98] Added a comment explaining the pure boolean subquery line --- xapian_backend.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xapian_backend.py b/xapian_backend.py index a0a3ee2..7ad0c78 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -895,7 +895,7 @@ class SearchQuery(BaseSearchQuery): DOCUMENT_CT_TERM_PREFIX, model._meta.app_label, model._meta.module_name ) - ), 0 + ), 0 # Pure boolean sub-query ) for model in self.models ] query = xapian.Query( From 2e3ed62c02321d856fc756f13d101a0282993fc5 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Mon, 30 Nov 2009 16:10:46 -0500 Subject: [PATCH 66/98] A whole lot of work on phrase and not operators. --- tests/xapian_tests/tests/xapian_query.py | 48 ++++++++-- xapian_backend.py | 113 +++++++++++++++++++++-- 2 files changed, 145 insertions(+), 16 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index 58e9ea2..e0bf462 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -45,6 +45,18 @@ class XapianSearchQueryTestCase(TestCase): self.sq.add_filter(SQ(content='hello')) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(hello)') + def test_build_query_single_word_not(self): + self.sq.add_filter(~SQ(content='hello')) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(( AND_NOT hello))') + + def test_build_query_single_word_field_exact(self): + self.sq.add_filter(SQ(foo='hello')) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(XFOOhello)') + + def test_build_query_single_word_field_exact_not(self): + self.sq.add_filter(~SQ(foo='hello')) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(( AND_NOT XFOOhello))') + def test_build_query_boolean(self): self.sq.add_filter(SQ(content=True)) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(true)') @@ -67,15 +79,33 @@ class XapianSearchQueryTestCase(TestCase): self.sq.add_filter(SQ(content='hello') | SQ(content='world')) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello OR world))') + def test_build_query_multiple_words_or_not(self): + self.sq.add_filter(~SQ(content='hello') | ~SQ(content='world')) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((( AND_NOT hello) OR ( AND_NOT world)))') + def test_build_query_multiple_words_mixed(self): self.sq.add_filter(SQ(content='why') | SQ(content='hello')) self.sq.add_filter(~SQ(content='world')) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(((why OR hello) AND ( AND_NOT world)))') + def test_build_query_multiple_word_field_exact(self): + self.sq.add_filter(SQ(foo='hello')) + self.sq.add_filter(SQ(bar='world')) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((XFOOhello AND XBARworld))') + + def test_build_query_multiple_word_field_exact_not(self): + self.sq.add_filter(~SQ(foo='hello')) + self.sq.add_filter(~SQ(bar='world')) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((( AND_NOT XFOOhello) AND ( AND_NOT XBARworld)))') + def test_build_query_phrase(self): self.sq.add_filter(SQ(content='hello world')) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(hello world)') + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello PHRASE 2 world))') + def test_build_query_phrase_not(self): + self.sq.add_filter(~SQ(content='hello world')) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(( AND_NOT (hello PHRASE 2 world)))') + def test_build_query_boost(self): self.sq.add_filter(SQ(content='hello')) self.sq.add_boost('world', 5) @@ -88,13 +118,13 @@ class XapianSearchQueryTestCase(TestCase): # self.sq.add_filter(SQ(created__lt='2009-02-12 12:13:00')) # self.sq.add_filter(SQ(title__gte='B')) # self.sq.add_filter(SQ(id__in=[1, 2, 3])) - # self.assertEqual(self.sq.build_query(), u'(why AND pub_date:[* TO "2009-02-10 01:59:00"] AND author:{daniel TO *} AND created:{* TO "2009-02-12 12:13:00"} AND title:[B TO *] AND (id:"1" OR id:"2" OR id:"3"))') - # - # def test_build_query_in_filter_multiple_words(self): - # self.sq.add_filter(SQ(content='why')) - # self.sq.add_filter(SQ(title__in=["A Famous Paper", "An Infamous Article"])) - # self.assertEqual(self.sq.build_query(), u'(why AND (title:"A Famous Paper" OR title:"An Infamous Article"))') - # + # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(why AND pub_date:[* TO "2009-02-10 01:59:00"] AND author:{daniel TO *} AND created:{* TO "2009-02-12 12:13:00"} AND title:[B TO *] AND (id:"1" OR id:"2" OR id:"3"))') + + def test_build_query_in_filter_multiple_words(self): + self.sq.add_filter(SQ(content='why')) + self.sq.add_filter(SQ(title__in=["A Famous Paper", "An Infamous Article"])) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((why AND (XTITLEa famous paper OR XTITLEan infamous article)))') + # def test_build_query_in_filter_datetime(self): # self.sq.add_filter(SQ(content='why')) # self.sq.add_filter(SQ(pub_date__in=[datetime.datetime(2009, 7, 6, 1, 56, 21)])) @@ -104,7 +134,7 @@ class XapianSearchQueryTestCase(TestCase): # self.sq.add_filter(SQ(content='why')) # self.sq.add_filter(SQ(title__startswith='haystack')) # self.assertEqual(self.sq.build_query(), u'(why AND title:haystack*)') - # + def test_clean(self): self.assertEqual(self.sq.clean('hello world'), 'hello world') self.assertEqual(self.sq.clean('hello AND world'), 'hello AND world') diff --git a/xapian_backend.py b/xapian_backend.py index 7ad0c78..db7ad99 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -931,13 +931,112 @@ class SearchQuery(BaseSearchQuery): ) else: expression, value = child - value = _marshal_value(value) - if is_not: - # DS_TODO: This can almost definitely be improved. - query_list.append(xapian.Query(xapian.Query.OP_AND_NOT, '', value)) + field, filter_type = search_node.split_expression(expression) + + if not isinstance(value, (list, tuple)): + value = _marshal_value(value) + + # if ' ' in value: + # phrase_query = [ + # xapian.Query( + # '%s%s%s' % ( + # DOCUMENT_CUSTOM_TERM_PREFIX, + # field.upper(), + # _marshal_value(term) + # ) + # ) for term in value.split() + # ] + # else: + # phrase_query = None + + if field == 'content': + if ' ' in value: + if is_not: + query_list.append( + xapian.Query( + xapian.Query.OP_AND_NOT, + xapian.Query(''), + xapian.Query(xapian.Query.OP_PHRASE, value.split()) + ) + ) + else: + query_list.append( + xapian.Query(xapian.Query.OP_PHRASE, value.split()) + ) + else: + if is_not: + query_list.append( + xapian.Query(xapian.Query.OP_AND_NOT, '', value) + ) + else: + query_list.append(xapian.Query(value)) else: - query_list.append(xapian.Query(value)) - + if filter_type == 'exact': + if ' ' in value: + if is_not: + query_list.append( + xapian.Query( + xapian.Query.OP_AND_NOT, + xapian.Query(''), + xapian.Query( + xapian.Query.OP_PHRASE, [ + '%s%s%s' % ( + DOCUMENT_CUSTOM_TERM_PREFIX, + field.upper(), _marshal_value(term) + ) for term in value.split() + ] + ) + ) + ) + else: + query_list.append( + xapian.Query( + xapian.Query.OP_PHRASE, [ + '%s%s%s' % ( + DOCUMENT_CUSTOM_TERM_PREFIX, + field.upper(), value + ) for term in value.split() + ] + ) + ) + else: + if is_not: + query_list.append( + xapian.Query( + xapian.Query. OP_AND_NOT, '', '%s%s%s' % (DOCUMENT_CUSTOM_TERM_PREFIX, field.upper(), value) + ) + ) + else: + query_list.append( + xapian.Query( + '%s%s%s' % (DOCUMENT_CUSTOM_TERM_PREFIX, field.upper(), value) + ) + ) + elif filter_type == 'gt': + pass + elif filter_type == 'gte': + pass + elif filter_type == 'lt': + pass + elif filter_type == 'lte': + pass + elif filter_type == 'startswith': + pass + elif filter_type == 'in': + subqueries = [ + xapian.Query( + '%s%s%s' % ( + DOCUMENT_CUSTOM_TERM_PREFIX, + field.upper(), + _marshal_value(possible_value) + ) + ) for possible_value in value + ] + query_list.append( + xapian.Query(xapian.Query.OP_OR, subqueries) + ) + + if search_node.connector == 'OR': return xapian.Query(xapian.Query.OP_OR, query_list) else: @@ -971,6 +1070,6 @@ def _marshal_value(value): elif isinstance(value, (int, long)): value = u'%012d' % value else: - value = force_unicode(value) + value = force_unicode(value).lower() return value From 99de351c79b97b17704367f1c9b51cc359d4880b Mon Sep 17 00:00:00 2001 From: David Sauve Date: Mon, 30 Nov 2009 16:20:05 -0500 Subject: [PATCH 67/98] Some minor formatting tweaks to code --- xapian_backend.py | 43 ++++++++++++++++--------------------------- 1 file changed, 16 insertions(+), 27 deletions(-) diff --git a/xapian_backend.py b/xapian_backend.py index db7ad99..34e1831 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -936,19 +936,6 @@ class SearchQuery(BaseSearchQuery): if not isinstance(value, (list, tuple)): value = _marshal_value(value) - # if ' ' in value: - # phrase_query = [ - # xapian.Query( - # '%s%s%s' % ( - # DOCUMENT_CUSTOM_TERM_PREFIX, - # field.upper(), - # _marshal_value(term) - # ) - # ) for term in value.split() - # ] - # else: - # phrase_query = None - if field == 'content': if ' ' in value: if is_not: @@ -956,7 +943,9 @@ class SearchQuery(BaseSearchQuery): xapian.Query( xapian.Query.OP_AND_NOT, xapian.Query(''), - xapian.Query(xapian.Query.OP_PHRASE, value.split()) + xapian.Query + (xapian.Query.OP_PHRASE, value.split() + ) ) ) else: @@ -982,7 +971,8 @@ class SearchQuery(BaseSearchQuery): xapian.Query.OP_PHRASE, [ '%s%s%s' % ( DOCUMENT_CUSTOM_TERM_PREFIX, - field.upper(), _marshal_value(term) + field.upper(), + _marshal_value(term) ) for term in value.split() ] ) @@ -1003,13 +993,19 @@ class SearchQuery(BaseSearchQuery): if is_not: query_list.append( xapian.Query( - xapian.Query. OP_AND_NOT, '', '%s%s%s' % (DOCUMENT_CUSTOM_TERM_PREFIX, field.upper(), value) + xapian.Query.OP_AND_NOT, '', '%s%s%s' % ( + DOCUMENT_CUSTOM_TERM_PREFIX, + field.upper(), value + ) ) ) else: query_list.append( xapian.Query( - '%s%s%s' % (DOCUMENT_CUSTOM_TERM_PREFIX, field.upper(), value) + '%s%s%s' % ( + DOCUMENT_CUSTOM_TERM_PREFIX, + field.upper(), value + ) ) ) elif filter_type == 'gt': @@ -1023,17 +1019,10 @@ class SearchQuery(BaseSearchQuery): elif filter_type == 'startswith': pass elif filter_type == 'in': - subqueries = [ - xapian.Query( - '%s%s%s' % ( - DOCUMENT_CUSTOM_TERM_PREFIX, - field.upper(), - _marshal_value(possible_value) - ) - ) for possible_value in value - ] query_list.append( - xapian.Query(xapian.Query.OP_OR, subqueries) + xapian.Query( + xapian.Query.OP_OR, [xapian.Query('%s%s%s' % (DOCUMENT_CUSTOM_TERM_PREFIX, field.upper(), _marshal_value(possible_value))) for possible_value in value] + ) ) From 2065ecee7f6a719532d4e6f8031d022176e57ab9 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Mon, 30 Nov 2009 16:34:40 -0500 Subject: [PATCH 68/98] Small refactor to make 'exact'more DRY --- tests/xapian_tests/tests/xapian_query.py | 5 +++ xapian_backend.py | 42 ++++++++++++------------ 2 files changed, 26 insertions(+), 21 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index e0bf462..1a3783f 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -125,6 +125,11 @@ class XapianSearchQueryTestCase(TestCase): self.sq.add_filter(SQ(title__in=["A Famous Paper", "An Infamous Article"])) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((why AND (XTITLEa famous paper OR XTITLEan infamous article)))') + # def test_build_query_not_in_filter_multiple_words(self): + # self.sq.add_filter(SQ(content='why')) + # self.sq.add_filter(~SQ(title__in=["A Famous Paper", "An Infamous Article"])) + # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((why AND_NOT (XTITLEa famous paper OR XTITLEan infamous article)))') + # def test_build_query_in_filter_datetime(self): # self.sq.add_filter(SQ(content='why')) # self.sq.add_filter(SQ(pub_date__in=[datetime.datetime(2009, 7, 6, 1, 56, 21)])) diff --git a/xapian_backend.py b/xapian_backend.py index 34e1831..56999e3 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -962,33 +962,25 @@ class SearchQuery(BaseSearchQuery): else: if filter_type == 'exact': if ' ' in value: + phrase_query = xapian.Query( + xapian.Query.OP_PHRASE, [ + '%s%s%s' % ( + DOCUMENT_CUSTOM_TERM_PREFIX, + field.upper(), _marshal_value(term) + ) for term in value.split() + ] + ) + if is_not: query_list.append( xapian.Query( xapian.Query.OP_AND_NOT, xapian.Query(''), - xapian.Query( - xapian.Query.OP_PHRASE, [ - '%s%s%s' % ( - DOCUMENT_CUSTOM_TERM_PREFIX, - field.upper(), - _marshal_value(term) - ) for term in value.split() - ] - ) + phrase_query ) ) else: - query_list.append( - xapian.Query( - xapian.Query.OP_PHRASE, [ - '%s%s%s' % ( - DOCUMENT_CUSTOM_TERM_PREFIX, - field.upper(), value - ) for term in value.split() - ] - ) - ) + query_list.append(phrase_query) else: if is_not: query_list.append( @@ -1021,10 +1013,18 @@ class SearchQuery(BaseSearchQuery): elif filter_type == 'in': query_list.append( xapian.Query( - xapian.Query.OP_OR, [xapian.Query('%s%s%s' % (DOCUMENT_CUSTOM_TERM_PREFIX, field.upper(), _marshal_value(possible_value))) for possible_value in value] + xapian.Query.OP_OR, [ + xapian.Query( + '%s%s%s' % ( + DOCUMENT_CUSTOM_TERM_PREFIX, + field.upper(), + _marshal_value(possible_value) + ) + ) for possible_value in value + ] ) ) - + if search_node.connector == 'OR': return xapian.Query(xapian.Query.OP_OR, query_list) From bbb38e3ef6cf5dac2aab4cc9a33c2cd9a0e385c0 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Mon, 30 Nov 2009 16:36:03 -0500 Subject: [PATCH 69/98] Small refactor to make even 'exact' more DRY --- xapian_backend.py | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/xapian_backend.py b/xapian_backend.py index 56999e3..171ada5 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -982,24 +982,19 @@ class SearchQuery(BaseSearchQuery): else: query_list.append(phrase_query) else: + term = '%s%s%s' % ( + DOCUMENT_CUSTOM_TERM_PREFIX, + field.upper(), value + ) + if is_not: query_list.append( xapian.Query( - xapian.Query.OP_AND_NOT, '', '%s%s%s' % ( - DOCUMENT_CUSTOM_TERM_PREFIX, - field.upper(), value - ) + xapian.Query.OP_AND_NOT, '', term ) ) else: - query_list.append( - xapian.Query( - '%s%s%s' % ( - DOCUMENT_CUSTOM_TERM_PREFIX, - field.upper(), value - ) - ) - ) + query_list.append(xapian.Query(term)) elif filter_type == 'gt': pass elif filter_type == 'gte': From f027e26644190d346ca46cc5e3f53d1d620bc967 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Mon, 30 Nov 2009 16:49:47 -0500 Subject: [PATCH 70/98] More refactor to keep things DRY --- xapian_backend.py | 102 +++++++++++++++++++++------------------------- 1 file changed, 46 insertions(+), 56 deletions(-) diff --git a/xapian_backend.py b/xapian_backend.py index 171ada5..70e0f3f 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -937,64 +937,10 @@ class SearchQuery(BaseSearchQuery): value = _marshal_value(value) if field == 'content': - if ' ' in value: - if is_not: - query_list.append( - xapian.Query( - xapian.Query.OP_AND_NOT, - xapian.Query(''), - xapian.Query - (xapian.Query.OP_PHRASE, value.split() - ) - ) - ) - else: - query_list.append( - xapian.Query(xapian.Query.OP_PHRASE, value.split()) - ) - else: - if is_not: - query_list.append( - xapian.Query(xapian.Query.OP_AND_NOT, '', value) - ) - else: - query_list.append(xapian.Query(value)) + query_list.append(self._content_field(value, is_not)) else: if filter_type == 'exact': - if ' ' in value: - phrase_query = xapian.Query( - xapian.Query.OP_PHRASE, [ - '%s%s%s' % ( - DOCUMENT_CUSTOM_TERM_PREFIX, - field.upper(), _marshal_value(term) - ) for term in value.split() - ] - ) - - if is_not: - query_list.append( - xapian.Query( - xapian.Query.OP_AND_NOT, - xapian.Query(''), - phrase_query - ) - ) - else: - query_list.append(phrase_query) - else: - term = '%s%s%s' % ( - DOCUMENT_CUSTOM_TERM_PREFIX, - field.upper(), value - ) - - if is_not: - query_list.append( - xapian.Query( - xapian.Query.OP_AND_NOT, '', term - ) - ) - else: - query_list.append(xapian.Query(term)) + query_list.append(self._filter_exact(value, field, is_not)) elif filter_type == 'gt': pass elif filter_type == 'gte': @@ -1026,6 +972,50 @@ class SearchQuery(BaseSearchQuery): else: return xapian.Query(xapian.Query.OP_AND, query_list) + def _content_field(self, value, is_not): + if ' ' in value: + if is_not: + return xapian.Query( + xapian.Query.OP_AND_NOT, + xapian.Query(''), + xapian.Query + (xapian.Query.OP_PHRASE, value.split() + ) + ) + else: + return xapian.Query(xapian.Query.OP_PHRASE, value.split()) + else: + if is_not: + return xapian.Query(xapian.Query.OP_AND_NOT, '', value) + else: + return xapian.Query(value) + + def _filter_exact(self, value, field, is_not): + if ' ' in value: + phrase_query = xapian.Query( + xapian.Query.OP_PHRASE, [ + '%s%s%s' % ( + DOCUMENT_CUSTOM_TERM_PREFIX, field.upper(), _marshal_value(term) + ) for term in value.split() + ] + ) + + if is_not: + return xapian.Query( + xapian.Query.OP_AND_NOT, xapian.Query(''), phrase_query + ) + else: + return phrase_query + else: + term = '%s%s%s' % ( + DOCUMENT_CUSTOM_TERM_PREFIX, field.upper(), value + ) + + if is_not: + return xapian.Query(xapian.Query.OP_AND_NOT, '', term) + else: + return xapian.Query(term) + def _marshal_value(value): """ From 09c12d88f7fd09d80c04998a90dc0be26c6be0ff Mon Sep 17 00:00:00 2001 From: David Sauve Date: Tue, 1 Dec 2009 08:58:34 -0500 Subject: [PATCH 71/98] Refactored some of the comon bits of query generation for phrase, all, and term based queries. Fixed 'in' based queries --- tests/xapian_tests/tests/xapian_query.py | 9 ++- xapian_backend.py | 93 ++++++++++++++---------- 2 files changed, 60 insertions(+), 42 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index 1a3783f..05fdd6f 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -120,16 +120,21 @@ class XapianSearchQueryTestCase(TestCase): # self.sq.add_filter(SQ(id__in=[1, 2, 3])) # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(why AND pub_date:[* TO "2009-02-10 01:59:00"] AND author:{daniel TO *} AND created:{* TO "2009-02-12 12:13:00"} AND title:[B TO *] AND (id:"1" OR id:"2" OR id:"3"))') + def test_build_query_in_filter_single_words(self): + self.sq.add_filter(SQ(content='why')) + self.sq.add_filter(SQ(title__in=["Dune", "Jaws"])) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((why AND (XTITLEdune OR XTITLEjaws)))') + def test_build_query_in_filter_multiple_words(self): self.sq.add_filter(SQ(content='why')) self.sq.add_filter(SQ(title__in=["A Famous Paper", "An Infamous Article"])) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((why AND (XTITLEa famous paper OR XTITLEan infamous article)))') + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((why AND ((XTITLEa PHRASE 3 XTITLEfamous PHRASE 3 XTITLEpaper) OR (XTITLEan PHRASE 3 XTITLEinfamous PHRASE 3 XTITLEarticle))))') # def test_build_query_not_in_filter_multiple_words(self): # self.sq.add_filter(SQ(content='why')) # self.sq.add_filter(~SQ(title__in=["A Famous Paper", "An Infamous Article"])) # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((why AND_NOT (XTITLEa famous paper OR XTITLEan infamous article)))') - + # # def test_build_query_in_filter_datetime(self): # self.sq.add_filter(SQ(content='why')) # self.sq.add_filter(SQ(pub_date__in=[datetime.datetime(2009, 7, 6, 1, 56, 21)])) diff --git a/xapian_backend.py b/xapian_backend.py index 70e0f3f..b4f2716 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -952,19 +952,7 @@ class SearchQuery(BaseSearchQuery): elif filter_type == 'startswith': pass elif filter_type == 'in': - query_list.append( - xapian.Query( - xapian.Query.OP_OR, [ - xapian.Query( - '%s%s%s' % ( - DOCUMENT_CUSTOM_TERM_PREFIX, - field.upper(), - _marshal_value(possible_value) - ) - ) for possible_value in value - ] - ) - ) + query_list.append(self._filter_in(value, field, is_not)) if search_node.connector == 'OR': @@ -976,50 +964,75 @@ class SearchQuery(BaseSearchQuery): if ' ' in value: if is_not: return xapian.Query( - xapian.Query.OP_AND_NOT, - xapian.Query(''), - xapian.Query - (xapian.Query.OP_PHRASE, value.split() - ) - ) + xapian.Query.OP_AND_NOT, self._all_query(), self._phrase_query(value.split()) + ) else: - return xapian.Query(xapian.Query.OP_PHRASE, value.split()) + return self._phrase_query(value.split()) else: if is_not: - return xapian.Query(xapian.Query.OP_AND_NOT, '', value) + return xapian.Query(xapian.Query.OP_AND_NOT, self._all_query(), self._term_query(value)) else: - return xapian.Query(value) + return self._term_query(value) def _filter_exact(self, value, field, is_not): if ' ' in value: - phrase_query = xapian.Query( - xapian.Query.OP_PHRASE, [ - '%s%s%s' % ( - DOCUMENT_CUSTOM_TERM_PREFIX, field.upper(), _marshal_value(term) - ) for term in value.split() - ] - ) - if is_not: return xapian.Query( - xapian.Query.OP_AND_NOT, xapian.Query(''), phrase_query + xapian.Query.OP_AND_NOT, self._all_query(), self._phrase_query(value.split(), field) ) else: - return phrase_query + return self._phrase_query(value.split(), field) else: - term = '%s%s%s' % ( - DOCUMENT_CUSTOM_TERM_PREFIX, field.upper(), value - ) - if is_not: - return xapian.Query(xapian.Query.OP_AND_NOT, '', term) + return xapian.Query(xapian.Query.OP_AND_NOT, self._all_query(), self._term_query(value, field)) else: - return xapian.Query(term) - + return self._term_query(value, field) + + def _filter_in(self, value_list, field, is_not): + query_list = [] + for value in value_list: + if ' ' in value: + query_list.append( + xapian.Query( + xapian.Query.OP_OR, self._phrase_query(value.split(), field) + ) + ) + else: + query_list.append( + xapian.Query( + xapian.Query.OP_OR, self._term_query(value, field) + ) + ) + return xapian.Query(xapian.Query.OP_OR, query_list) + + def _all_query(self): + return xapian.Query('') + + def _term_query(self, value, field=None): + if field: + return xapian.Query('%s%s%s' % ( + DOCUMENT_CUSTOM_TERM_PREFIX, field.upper(), _marshal_value(value) + ) + ) + else: + return xapian.Query(value) + + def _phrase_query(self, value_list, field=None): + if field: + return xapian.Query( + xapian.Query.OP_PHRASE, [ + '%s%s%s' % ( + DOCUMENT_CUSTOM_TERM_PREFIX, field.upper(), _marshal_value(value) + ) for value in value_list + ] + ) + else: + return xapian.Query(xapian.Query.OP_PHRASE, value_list) + def _marshal_value(value): """ - Private method that converts Python values to a string for Xapian values. + Private utility method that converts Python values to a string for Xapian values. """ if isinstance(value, datetime.datetime): if value.microsecond: From d197014a8273561b6e8043f91c8a5d951b965f69 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Tue, 1 Dec 2009 09:11:01 -0500 Subject: [PATCH 72/98] Added support for not in 'in' based queries --- tests/xapian_tests/tests/xapian_query.py | 15 ++++++++++----- xapian_backend.py | 5 ++++- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index 05fdd6f..3b0c115 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -125,16 +125,21 @@ class XapianSearchQueryTestCase(TestCase): self.sq.add_filter(SQ(title__in=["Dune", "Jaws"])) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((why AND (XTITLEdune OR XTITLEjaws)))') + def test_build_query_not_in_filter_single_words(self): + self.sq.add_filter(SQ(content='why')) + self.sq.add_filter(~SQ(title__in=["Dune", "Jaws"])) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((why AND ( AND_NOT (XTITLEdune OR XTITLEjaws))))') + def test_build_query_in_filter_multiple_words(self): self.sq.add_filter(SQ(content='why')) self.sq.add_filter(SQ(title__in=["A Famous Paper", "An Infamous Article"])) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((why AND ((XTITLEa PHRASE 3 XTITLEfamous PHRASE 3 XTITLEpaper) OR (XTITLEan PHRASE 3 XTITLEinfamous PHRASE 3 XTITLEarticle))))') - # def test_build_query_not_in_filter_multiple_words(self): - # self.sq.add_filter(SQ(content='why')) - # self.sq.add_filter(~SQ(title__in=["A Famous Paper", "An Infamous Article"])) - # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((why AND_NOT (XTITLEa famous paper OR XTITLEan infamous article)))') - # + def test_build_query_not_in_filter_multiple_words(self): + self.sq.add_filter(SQ(content='why')) + self.sq.add_filter(~SQ(title__in=["A Famous Paper", "An Infamous Article"])) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((why AND ( AND_NOT ((XTITLEa PHRASE 3 XTITLEfamous PHRASE 3 XTITLEpaper) OR (XTITLEan PHRASE 3 XTITLEinfamous PHRASE 3 XTITLEarticle)))))') + # def test_build_query_in_filter_datetime(self): # self.sq.add_filter(SQ(content='why')) # self.sq.add_filter(SQ(pub_date__in=[datetime.datetime(2009, 7, 6, 1, 56, 21)])) diff --git a/xapian_backend.py b/xapian_backend.py index b4f2716..62ebb91 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -1003,7 +1003,10 @@ class SearchQuery(BaseSearchQuery): xapian.Query.OP_OR, self._term_query(value, field) ) ) - return xapian.Query(xapian.Query.OP_OR, query_list) + if is_not: + return xapian.Query(xapian.Query.OP_AND_NOT, self._all_query(), xapian.Query(xapian.Query.OP_OR, query_list)) + else: + return xapian.Query(xapian.Query.OP_OR, query_list) def _all_query(self): return xapian.Query('') From 2dd8104abfa45fd15ddf1d882f4c6f46dae1b059 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Tue, 1 Dec 2009 09:19:30 -0500 Subject: [PATCH 73/98] Added some docstrings to private methods that should make their uses more apparent --- xapian_backend.py | 64 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 63 insertions(+), 1 deletion(-) diff --git a/xapian_backend.py b/xapian_backend.py index 62ebb91..d7a5d65 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -954,13 +954,23 @@ class SearchQuery(BaseSearchQuery): elif filter_type == 'in': query_list.append(self._filter_in(value, field, is_not)) - if search_node.connector == 'OR': return xapian.Query(xapian.Query.OP_OR, query_list) else: return xapian.Query(xapian.Query.OP_AND, query_list) def _content_field(self, value, is_not): + """ + Private method that returns a xapian.Query that searches for `value` + in all fields. + + Required arguments: + ``value`` -- The value to search for + ``is_not`` -- Invert the search results + + Returns: + A xapian.Query + """ if ' ' in value: if is_not: return xapian.Query( @@ -975,6 +985,18 @@ class SearchQuery(BaseSearchQuery): return self._term_query(value) def _filter_exact(self, value, field, is_not): + """ + Private method that returns a xapian.Query that searches for `value` + in a specified `field`. + + Required arguments: + ``value`` -- The value to search for + ``field`` -- The field to search + ``is_not`` -- Invert the search results + + Returns: + A xapian.Query + """ if ' ' in value: if is_not: return xapian.Query( @@ -989,6 +1011,18 @@ class SearchQuery(BaseSearchQuery): return self._term_query(value, field) def _filter_in(self, value_list, field, is_not): + """ + Private method that returns a xapian.Query that searches for any value + of `value_list` in a specified `field`. + + Required arguments: + ``value_list`` -- The values to search for + ``field`` -- The field to search + ``is_not`` -- Invert the search results + + Returns: + A xapian.Query + """ query_list = [] for value in value_list: if ' ' in value: @@ -1009,9 +1043,26 @@ class SearchQuery(BaseSearchQuery): return xapian.Query(xapian.Query.OP_OR, query_list) def _all_query(self): + """ + Private method that returns a xapian.Query that returns all documents, + + Returns: + A xapian.Query + """ return xapian.Query('') def _term_query(self, value, field=None): + """ + Private method that returns a term based xapian.Query that searches + for term `value`. + + Required arguments: + ``value`` -- The value to search for + ``field`` -- The field to search (If `None`, all fields) + + Returns: + A xapian.Query + """ if field: return xapian.Query('%s%s%s' % ( DOCUMENT_CUSTOM_TERM_PREFIX, field.upper(), _marshal_value(value) @@ -1021,6 +1072,17 @@ class SearchQuery(BaseSearchQuery): return xapian.Query(value) def _phrase_query(self, value_list, field=None): + """ + Private method that returns a phrase based xapian.Query that searches + for terms in `value_list. + + Required arguments: + ``value_list`` -- The values to search for + ``field`` -- The field to search (If `None`, all fields) + + Returns: + A xapian.Query + """ if field: return xapian.Query( xapian.Query.OP_PHRASE, [ From c6dd7b5deb9b1475f3215890c282a7a1f13d7740 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Tue, 1 Dec 2009 15:55:22 -0500 Subject: [PATCH 74/98] Updated to GPLv3 to maintain compatibility with Apache license --- LICENSE | 842 ++++++++++++++------- tests/xapian_settings.py | 16 +- tests/xapian_tests/__init__.py | 16 +- tests/xapian_tests/models.py | 16 +- tests/xapian_tests/tests/__init__.py | 17 +- tests/xapian_tests/tests/xapian_backend.py | 16 +- tests/xapian_tests/tests/xapian_query.py | 16 +- xapian_backend.py | 16 +- 8 files changed, 570 insertions(+), 385 deletions(-) diff --git a/LICENSE b/LICENSE index d511905..94a0453 100644 --- a/LICENSE +++ b/LICENSE @@ -1,339 +1,621 @@ - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 - Copyright (C) 1989, 1991 Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. - Preamble + Preamble - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Lesser General Public License instead.) You can apply it to + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + TERMS AND CONDITIONS - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". + 0. Definitions. -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. + "This License" refers to version 3 of the GNU General Public License. - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. + A "covered work" means either the unmodified Program or a work based +on the Program. - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. + 1. Source Code. -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. + The Corresponding Source for a work in source code form is that +same work. -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. + 2. Basic Permissions. - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of this License. - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. + 13. Use with the GNU Affero General Public License. -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. + 14. Revised Versions of this License. - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. - NO WARRANTY + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. + 15. Disclaimer of Warranty. - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - END OF TERMS AND CONDITIONS + 16. Limitation of Liability. - How to Apply These Terms to Your New Programs + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. + 17. Interpretation of Sections 15 and 16. - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. - - Copyright (C) - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along - with this program; if not, write to the Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - - Gnomovision version 69, Copyright (C) year name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - , 1 April 1989 - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. + END OF TERMS AND CONDITIONS diff --git a/tests/xapian_settings.py b/tests/xapian_settings.py index 60d1066..6e61cd7 100644 --- a/tests/xapian_settings.py +++ b/tests/xapian_settings.py @@ -1,18 +1,4 @@ -# Copyright (C) 2009 David Sauve -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 2 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License along -# with this program; if not, write to the Free Software Foundation, Inc., -# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +# Copyright (C) 2009 David Sauve, Trapeze import os from settings import * diff --git a/tests/xapian_tests/__init__.py b/tests/xapian_tests/__init__.py index 02b1d14..07260c5 100644 --- a/tests/xapian_tests/__init__.py +++ b/tests/xapian_tests/__init__.py @@ -1,15 +1 @@ -# Copyright (C) 2009 David Sauve -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 2 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License along -# with this program; if not, write to the Free Software Foundation, Inc., -# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +# Copyright (C) 2009 David Sauve, Trapeze \ No newline at end of file diff --git a/tests/xapian_tests/models.py b/tests/xapian_tests/models.py index 02b1d14..07260c5 100644 --- a/tests/xapian_tests/models.py +++ b/tests/xapian_tests/models.py @@ -1,15 +1 @@ -# Copyright (C) 2009 David Sauve -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 2 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License along -# with this program; if not, write to the Free Software Foundation, Inc., -# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +# Copyright (C) 2009 David Sauve, Trapeze \ No newline at end of file diff --git a/tests/xapian_tests/tests/__init__.py b/tests/xapian_tests/tests/__init__.py index 5b721c7..809a295 100644 --- a/tests/xapian_tests/tests/__init__.py +++ b/tests/xapian_tests/tests/__init__.py @@ -1,18 +1,5 @@ -# Copyright (C) 2009 David Sauve -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 2 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License along -# with this program; if not, write to the Free Software Foundation, Inc., -# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +# Copyright (C) 2009 David Sauve, Trapeze + import warnings warnings.simplefilter('ignore', Warning) diff --git a/tests/xapian_tests/tests/xapian_backend.py b/tests/xapian_tests/tests/xapian_backend.py index 173d29e..dc7e45a 100644 --- a/tests/xapian_tests/tests/xapian_backend.py +++ b/tests/xapian_tests/tests/xapian_backend.py @@ -1,18 +1,4 @@ -# Copyright (C) 2009 David Sauve -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 2 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License along -# with this program; if not, write to the Free Software Foundation, Inc., -# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +# Copyright (C) 2009 David Sauve, Trapeze import cPickle as pickle import datetime diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index 3b0c115..24c984b 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -1,18 +1,4 @@ -# Copyright (C) 2009 David Sauve -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 2 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License along -# with this program; if not, write to the Free Software Foundation, Inc., -# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +# Copyright (C) 2009 David Sauve, Trapeze import datetime import os diff --git a/xapian_backend.py b/xapian_backend.py index d7a5d65..f225af9 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -1,18 +1,4 @@ -# Copyright (C) 2009 David Sauve -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 2 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License along -# with this program; if not, write to the Free Software Foundation, Inc., -# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +# Copyright (C) 2009 David Sauve, Trapeze __author__ = 'David Sauve' __version__ = (2, 0, 0, 'alpha') From 4b0f6520f1022b7e0a0287d54b8c90dc3dcab93a Mon Sep 17 00:00:00 2001 From: David Sauve Date: Wed, 2 Dec 2009 11:47:26 -0500 Subject: [PATCH 75/98] Re-added xapian_backend tests. This is in a really rough state right now. Most tests are commented out. --- tests/xapian_tests/tests/__init__.py | 2 +- tests/xapian_tests/tests/xapian_backend.py | 462 ++++++++++----------- tests/xapian_tests/tests/xapian_query.py | 18 +- xapian_backend.py | 202 +-------- 4 files changed, 261 insertions(+), 423 deletions(-) diff --git a/tests/xapian_tests/tests/__init__.py b/tests/xapian_tests/tests/__init__.py index 809a295..51a6a8d 100644 --- a/tests/xapian_tests/tests/__init__.py +++ b/tests/xapian_tests/tests/__init__.py @@ -5,4 +5,4 @@ import warnings warnings.simplefilter('ignore', Warning) from xapian_tests.tests.xapian_query import * -# from xapian_tests.tests.xapian_backend import * +from xapian_tests.tests.xapian_backend import * diff --git a/tests/xapian_tests/tests/xapian_backend.py b/tests/xapian_tests/tests/xapian_backend.py index dc7e45a..b1f44f7 100644 --- a/tests/xapian_tests/tests/xapian_backend.py +++ b/tests/xapian_tests/tests/xapian_backend.py @@ -12,7 +12,7 @@ from django.utils.encoding import force_unicode from django.test import TestCase from haystack import indexes, sites -from haystack.backends.xapian_backend import SearchBackend +from haystack.backends.xapian_backend import SearchBackend, _marshal_value from core.models import MockTag, AnotherMockModel @@ -115,253 +115,253 @@ class XapianSearchBackendTestCase(TestCase): return document_list - def test_update(self): - self.sb.update(self.msi, self.sample_objs) - self.sb.update(self.msi, self.sample_objs) # Duplicates should be updated, not appended -- http://github.com/notanumber/xapian-haystack/issues/#issue/6 - - self.assertEqual(len(self.xapian_search('')), 3) - self.assertEqual([dict(doc) for doc in self.xapian_search('')], [ - {'flag': u't', 'name': u'david1', 'text': u'Indexed!\n1', 'sites': u"['1', '2', '3']", 'pub_date': u'20090224000000', 'value': u'000000000005', 'id': u'tests.xapianmockmodel.1', 'slug': u'http://example.com/1', 'popularity': '\xca\x84', 'django_id': u'1', 'django_ct': u'tests.xapianmockmodel'}, - {'flag': u'f', 'name': u'david2', 'text': u'Indexed!\n2', 'sites': u"['2', '4', '6']", 'pub_date': u'20090223000000', 'value': u'000000000010', 'id': u'tests.xapianmockmodel.2', 'slug': u'http://e - {'flag': u't', 'name': u'david3', 'text': u'Indexed!\n3', 'sites': u"['3', '6', '9']", 'pub_date': u'20090222000000', 'value': u'000000000015', 'id': u'tests.xapianmockmodel.3', 'slug': u'http://example.com/3', 'popularity': '\xcb\x98', 'django_id': u'3', 'django_ct': u'tests.xapianmockmodel'} - ]) + # def test_update(self): + # self.sb.update(self.msi, self.sample_objs) + # self.sb.update(self.msi, self.sample_objs) # Duplicates should be updated, not appended -- http://github.com/notanumber/xapian-haystack/issues/#issue/6 + # + # self.assertEqual(len(self.xapian_search('')), 3) + # self.assertEqual([dict(doc) for doc in self.xapian_search('')], [ + # {'flag': u't', 'name': u'david1', 'text': u'Indexed!\n1', 'sites': u"['1', '2', '3']", 'pub_date': u'20090224000000', 'value': u'000000000005', 'id': u'tests.xapianmockmodel.1', 'slug': u'http://example.com/1', 'popularity': '\xca\x84', 'django_id': u'1', 'django_ct': u'tests.xapianmockmodel'}, + # {'flag': u'f', 'name': u'david2', 'text': u'Indexed!\n2', 'sites': u"['2', '4', '6']", 'pub_date': u'20090223000000', 'value': u'000000000010', 'id': u'tests.xapianmockmodel.2', 'slug': u'http://e + # {'flag': u't', 'name': u'david3', 'text': u'Indexed!\n3', 'sites': u"['3', '6', '9']", 'pub_date': u'20090222000000', 'value': u'000000000015', 'id': u'tests.xapianmockmodel.3', 'slug': u'http://example.com/3', 'popularity': '\xcb\x98', 'django_id': u'3', 'django_ct': u'tests.xapianmockmodel'} + # ]) - def test_remove(self): - self.sb.update(self.msi, self.sample_objs) - self.assertEqual(len(self.xapian_search('')), 3) - - self.sb.remove(self.sample_objs[0]) - self.assertEqual(len(self.xapian_search('')), 2) - self.assertEqual([dict(doc) for doc in self.xapian_search('')], [ - {'flag': u'f', 'name': u'david2', 'text': u'Indexed!\n2', 'sites': u"['2', '4', '6']", 'pub_date': u'20090223000000', 'value': u'000000000010', 'id': u'tests.xapianmockmodel.2', 'slug': u'http://e - {'flag': u't', 'name': u'david3', 'text': u'Indexed!\n3', 'sites': u"['3', '6', '9']", 'pub_date': u'20090222000000', 'value': u'000000000015', 'id': u'tests.xapianmockmodel.3', 'slug': u'http://example.com/3', 'popularity': '\xcb\x98', 'django_id': u'3', 'django_ct': u'tests.xapianmockmodel'} - ]) + # def test_remove(self): + # self.sb.update(self.msi, self.sample_objs) + # self.assertEqual(len(self.xapian_search('')), 3) + # + # self.sb.remove(self.sample_objs[0]) + # self.assertEqual(len(self.xapian_search('')), 2) + # self.assertEqual([dict(doc) for doc in self.xapian_search('')], [ + # {'flag': u'f', 'name': u'david2', 'text': u'Indexed!\n2', 'sites': u"['2', '4', '6']", 'pub_date': u'20090223000000', 'value': u'000000000010', 'id': u'tests.xapianmockmodel.2', 'slug': u'http://e + # {'flag': u't', 'name': u'david3', 'text': u'Indexed!\n3', 'sites': u"['3', '6', '9']", 'pub_date': u'20090222000000', 'value': u'000000000015', 'id': u'tests.xapianmockmodel.3', 'slug': u'http://example.com/3', 'popularity': '\xcb\x98', 'django_id': u'3', 'django_ct': u'tests.xapianmockmodel'} + # ]) - def test_clear(self): - self.sb.update(self.msi, self.sample_objs) - self.assertEqual(len(self.xapian_search('')), 3) - - self.sb.clear() - self.assertEqual(len(self.xapian_search('')), 0) - - self.sb.update(self.msi, self.sample_objs) - self.assertEqual(len(self.xapian_search('')), 3) - - self.sb.clear([AnotherMockModel]) - self.assertEqual(len(self.xapian_search('')), 3) - - self.sb.clear([XapianMockModel]) - self.assertEqual(len(self.xapian_search('')), 0) - - self.sb.update(self.msi, self.sample_objs) - self.assertEqual(len(self.xapian_search('')), 3) - - self.sb.clear([AnotherMockModel, XapianMockModel]) - self.assertEqual(len(self.xapian_search('')), 0) + # def test_clear(self): + # self.sb.update(self.msi, self.sample_objs) + # self.assertEqual(len(self.xapian_search('')), 3) + # + # self.sb.clear() + # self.assertEqual(len(self.xapian_search('')), 0) + # + # self.sb.update(self.msi, self.sample_objs) + # self.assertEqual(len(self.xapian_search('')), 3) + # + # self.sb.clear([AnotherMockModel]) + # self.assertEqual(len(self.xapian_search('')), 3) + # + # self.sb.clear([XapianMockModel]) + # self.assertEqual(len(self.xapian_search('')), 0) + # + # self.sb.update(self.msi, self.sample_objs) + # self.assertEqual(len(self.xapian_search('')), 3) + # + # self.sb.clear([AnotherMockModel, XapianMockModel]) + # self.assertEqual(len(self.xapian_search('')), 0) - def test_search(self): - self.sb.update(self.msi, self.sample_objs) - self.assertEqual(len(self.xapian_search('')), 3) - - # Empty query - self.assertEqual(self.sb.search(''), {'hits': 0, 'results': []}) - - # Wildcard -- All - self.assertEqual(self.sb.search('*')['hits'], 3) - self.assertEqual([result.pk for result in self.sb.search('*')['results']], [1, 2, 3]) - - # Exact match - self.assertEqual([result.pk for result in self.sb.search('name:david2')['results']], [2]) - self.assertEqual([result.pk for result in self.sb.search('value:10')['results']], [2]) - self.assertEqual([result.pk for result in self.sb.search('flag:false')['results']], [2]) - self.assertEqual([result.pk for result in self.sb.search('popularity:35.5')['results']], [2]) - - # NOT operator - self.assertEqual([result.pk for result in self.sb.search('NOT name:david1')['results']], [2, 3]) - self.assertEqual([result.pk for result in self.sb.search('NOT name:david1 AND index')['results']], [2, 3]) - self.assertEqual([result.pk for result in self.sb.search('index NOT name:david1')['results']], [2, 3]) - self.assertEqual([result.pk for result in self.sb.search('index NOT name:david1 NOT name:david2')['results']], [3]) - self.assertEqual([result.pk for result in self.sb.search('NOT name:david1 NOT name:david2')['results']], [3]) + # def test_search(self): + # self.sb.update(self.msi, self.sample_objs) + # self.assertEqual(len(self.xapian_search('')), 3) + # + # # Empty query + # self.assertEqual(self.sb.search(''), {'hits': 0, 'results': []}) + # + # # Wildcard -- All + # self.assertEqual(self.sb.search('*')['hits'], 3) + # self.assertEqual([result.pk for result in self.sb.search('*')['results']], [1, 2, 3]) + # + # # Exact match + # self.assertEqual([result.pk for result in self.sb.search('name:david2')['results']], [2]) + # self.assertEqual([result.pk for result in self.sb.search('value:10')['results']], [2]) + # self.assertEqual([result.pk for result in self.sb.search('flag:false')['results']], [2]) + # self.assertEqual([result.pk for result in self.sb.search('popularity:35.5')['results']], [2]) + # + # # NOT operator + # self.assertEqual([result.pk for result in self.sb.search('NOT name:david1')['results']], [2, 3]) + # self.assertEqual([result.pk for result in self.sb.search('NOT name:david1 AND index')['results']], [2, 3]) + # self.assertEqual([result.pk for result in self.sb.search('index NOT name:david1')['results']], [2, 3]) + # self.assertEqual([result.pk for result in self.sb.search('index NOT name:david1 NOT name:david2')['results']], [3]) + # self.assertEqual([result.pk for result in self.sb.search('NOT name:david1 NOT name:david2')['results']], [3]) + # + # # Ranges + # self.assertEqual([result.pk for result in self.sb.search('index name:david2..david3')['results']], [2, 3]) + # self.assertEqual([result.pk for result in self.sb.search('index name:..david2')['results']], [1, 2]) + # self.assertEqual([result.pk for result in self.sb.search('index name:david2..*')['results']], [2, 3]) + # self.assertEqual([result.pk for result in self.sb.search('index pub_date:20090222000000..20090223000000')['results']], [2, 3]) + # self.assertEqual([result.pk for result in self.sb.search('index pub_date:..20090223000000')['results']], [2, 3]) + # self.assertEqual([result.pk for result in self.sb.search('index pub_date:20090223000000..*')['results']], [1, 2]) + # self.assertEqual([result.pk for result in self.sb.search('index value:10..15')['results']], [2, 3]) + # self.assertEqual([result.pk for result in self.sb.search('index value:..10')['results']], [1, 2]) + # self.assertEqual([result.pk for result in self.sb.search('index value:10..*')['results']], [2, 3]) + # self.assertEqual([result.pk for result in self.sb.search('index popularity:..100.0')['results']], [2]) + # self.assertEqual([result.pk for result in self.sb.search('index popularity:100.0..*')['results']], [1, 3]) - # Ranges - self.assertEqual([result.pk for result in self.sb.search('index name:david2..david3')['results']], [2, 3]) - self.assertEqual([result.pk for result in self.sb.search('index name:..david2')['results']], [1, 2]) - self.assertEqual([result.pk for result in self.sb.search('index name:david2..*')['results']], [2, 3]) - self.assertEqual([result.pk for result in self.sb.search('index pub_date:20090222000000..20090223000000')['results']], [2, 3]) - self.assertEqual([result.pk for result in self.sb.search('index pub_date:..20090223000000')['results']], [2, 3]) - self.assertEqual([result.pk for result in self.sb.search('index pub_date:20090223000000..*')['results']], [1, 2]) - self.assertEqual([result.pk for result in self.sb.search('index value:10..15')['results']], [2, 3]) - self.assertEqual([result.pk for result in self.sb.search('index value:..10')['results']], [1, 2]) - self.assertEqual([result.pk for result in self.sb.search('index value:10..*')['results']], [2, 3]) - self.assertEqual([result.pk for result in self.sb.search('index popularity:..100.0')['results']], [2]) - self.assertEqual([result.pk for result in self.sb.search('index popularity:100.0..*')['results']], [1, 3]) - - def test_field_facets(self): - self.sb.update(self.msi, self.sample_objs) - self.assertEqual(len(self.xapian_search('')), 3) - - self.assertEqual(self.sb.search('', facets=['name']), {'hits': 0, 'results': []}) - results = self.sb.search('index', facets=['name']) - self.assertEqual(results['hits'], 3) - self.assertEqual(results['facets']['fields']['name'], [('david1', 1), ('david2', 1), ('david3', 1)]) - - results = self.sb.search('index', facets=['flag']) - self.assertEqual(results['hits'], 3) - self.assertEqual(results['facets']['fields']['flag'], [(False, 1), (True, 2)]) - - results = self.sb.search('index', facets=['sites']) - self.assertEqual(results['hits'], 3) - self.assertEqual(results['facets']['fields']['sites'], [('1', 1), ('3', 2), ('2', 2), ('4', 1), ('6', 2), ('9', 1)]) + # def test_field_facets(self): + # self.sb.update(self.msi, self.sample_objs) + # self.assertEqual(len(self.xapian_search('')), 3) + # + # self.assertEqual(self.sb.search('', facets=['name']), {'hits': 0, 'results': []}) + # results = self.sb.search('index', facets=['name']) + # self.assertEqual(results['hits'], 3) + # self.assertEqual(results['facets']['fields']['name'], [('david1', 1), ('david2', 1), ('david3', 1)]) + # + # results = self.sb.search('index', facets=['flag']) + # self.assertEqual(results['hits'], 3) + # self.assertEqual(results['facets']['fields']['flag'], [(False, 1), (True, 2)]) + # + # results = self.sb.search('index', facets=['sites']) + # self.assertEqual(results['hits'], 3) + # self.assertEqual(results['facets']['fields']['sites'], [('1', 1), ('3', 2), ('2', 2), ('4', 1), ('6', 2), ('9', 1)]) - def test_date_facets(self): - self.sb.update(self.msi, self.sample_objs) - self.assertEqual(len(self.xapian_search('')), 3) + # def test_date_facets(self): + # self.sb.update(self.msi, self.sample_objs) + # self.assertEqual(len(self.xapian_search('')), 3) + # + # self.assertEqual(self.sb.search('', date_facets={'pub_date': {'start_date': datetime.datetime(2008, 10, 26), 'end_date': datetime.datetime(2009, 3, 26), 'gap_by': 'month'}}), {'hits': 0, 'results': []}) + # results = self.sb.search('index', date_facets={'pub_date': {'start_date': datetime.datetime(2008, 10, 26), 'end_date': datetime.datetime(2009, 3, 26), 'gap_by': 'month'}}) + # self.assertEqual(results['hits'], 3) + # self.assertEqual(results['facets']['dates']['pub_date'], [ + # ('2009-02-26T00:00:00', 0), + # ('2009-01-26T00:00:00', 3), + # ('2008-12-26T00:00:00', 0), + # ('2008-11-26T00:00:00', 0), + # ('2008-10-26T00:00:00', 0), + # ]) + # + # results = self.sb.search('index', date_facets={'pub_date': {'start_date': datetime.datetime(2009, 02, 01), 'end_date': datetime.datetime(2009, 3, 15), 'gap_by': 'day', 'gap_amount': 15}}) + # self.assertEqual(results['hits'], 3) + # self.assertEqual(results['facets']['dates']['pub_date'], [ + # ('2009-03-03T00:00:00', 0), + # ('2009-02-16T00:00:00', 3), + # ('2009-02-01T00:00:00', 0) + # ]) - self.assertEqual(self.sb.search('', date_facets={'pub_date': {'start_date': datetime.datetime(2008, 10, 26), 'end_date': datetime.datetime(2009, 3, 26), 'gap_by': 'month'}}), {'hits': 0, 'results': []}) - results = self.sb.search('index', date_facets={'pub_date': {'start_date': datetime.datetime(2008, 10, 26), 'end_date': datetime.datetime(2009, 3, 26), 'gap_by': 'month'}}) - self.assertEqual(results['hits'], 3) - self.assertEqual(results['facets']['dates']['pub_date'], [ - ('2009-02-26T00:00:00', 0), - ('2009-01-26T00:00:00', 3), - ('2008-12-26T00:00:00', 0), - ('2008-11-26T00:00:00', 0), - ('2008-10-26T00:00:00', 0), - ]) - - results = self.sb.search('index', date_facets={'pub_date': {'start_date': datetime.datetime(2009, 02, 01), 'end_date': datetime.datetime(2009, 3, 15), 'gap_by': 'day', 'gap_amount': 15}}) - self.assertEqual(results['hits'], 3) - self.assertEqual(results['facets']['dates']['pub_date'], [ - ('2009-03-03T00:00:00', 0), - ('2009-02-16T00:00:00', 3), - ('2009-02-01T00:00:00', 0) - ]) - - def test_query_facets(self): - self.sb.update(self.msi, self.sample_objs) - self.assertEqual(len(self.xapian_search('')), 3) - - self.assertEqual(self.sb.search('', query_facets={'name': 'da*'}), {'hits': 0, 'results': []}) - results = self.sb.search('index', query_facets={'name': 'da*'}) - self.assertEqual(results['hits'], 3) - self.assertEqual(results['facets']['queries']['name'], ('da*', 3)) + # def test_query_facets(self): + # self.sb.update(self.msi, self.sample_objs) + # self.assertEqual(len(self.xapian_search('')), 3) + # + # self.assertEqual(self.sb.search('', query_facets={'name': 'da*'}), {'hits': 0, 'results': []}) + # results = self.sb.search('index', query_facets={'name': 'da*'}) + # self.assertEqual(results['hits'], 3) + # self.assertEqual(results['facets']['queries']['name'], ('da*', 3)) - def test_narrow_queries(self): - self.sb.update(self.msi, self.sample_objs) - self.assertEqual(len(self.xapian_search('')), 3) - - self.assertEqual(self.sb.search('', narrow_queries=set(['name:david1'])), {'hits': 0, 'results': []}) - results = self.sb.search('index', narrow_queries=set(['name:david1'])) - self.assertEqual(results['hits'], 1) + # def test_narrow_queries(self): + # self.sb.update(self.msi, self.sample_objs) + # self.assertEqual(len(self.xapian_search('')), 3) + # + # self.assertEqual(self.sb.search('', narrow_queries=set(['name:david1'])), {'hits': 0, 'results': []}) + # results = self.sb.search('index', narrow_queries=set(['name:david1'])) + # self.assertEqual(results['hits'], 1) - def test_highlight(self): - self.sb.update(self.msi, self.sample_objs) - self.assertEqual(len(self.xapian_search('')), 3) - - self.assertEqual(self.sb.search('', highlight=True), {'hits': 0, 'results': []}) - self.assertEqual(self.sb.search('Index', highlight=True)['hits'], 3) - self.assertEqual([result.highlighted['text'] for result in self.sb.search('Index', highlight=True)['results']], ['Indexed!\n1', 'Indexed!\n2', 'Indexed!\n3']) + # def test_highlight(self): + # self.sb.update(self.msi, self.sample_objs) + # self.assertEqual(len(self.xapian_search('')), 3) + # + # self.assertEqual(self.sb.search('', highlight=True), {'hits': 0, 'results': []}) + # self.assertEqual(self.sb.search('Index', highlight=True)['hits'], 3) + # self.assertEqual([result.highlighted['text'] for result in self.sb.search('Index', highlight=True)['results']], ['Indexed!\n1', 'Indexed!\n2', 'Indexed!\n3']) - def test_spelling_suggestion(self): - self.sb.update(self.msi, self.sample_objs) - self.assertEqual(len(self.xapian_search('')), 3) + # def test_spelling_suggestion(self): + # self.sb.update(self.msi, self.sample_objs) + # self.assertEqual(len(self.xapian_search('')), 3) + # + # self.assertEqual(self.sb.search('indxe')['hits'], 0) + # self.assertEqual(self.sb.search('indxe')['spelling_suggestion'], 'indexed') + # + # self.assertEqual(self.sb.search('indxed')['hits'], 0) + # self.assertEqual(self.sb.search('indxed')['spelling_suggestion'], 'indexed') + # + # self.assertEqual(self.sb.search('indx')['hits'], 0) + # self.assertEqual(self.sb.search('indx', spelling_query='indexy')['spelling_suggestion'], 'indexed') - self.assertEqual(self.sb.search('indxe')['hits'], 0) - self.assertEqual(self.sb.search('indxe')['spelling_suggestion'], 'indexed') - - self.assertEqual(self.sb.search('indxed')['hits'], 0) - self.assertEqual(self.sb.search('indxed')['spelling_suggestion'], 'indexed') - - self.assertEqual(self.sb.search('indx')['hits'], 0) - self.assertEqual(self.sb.search('indx', spelling_query='indexy')['spelling_suggestion'], 'indexed') - - def test_stemming(self): - self.sb.update(self.msi, self.sample_objs) - self.assertEqual(len(self.xapian_search('')), 3) - - results = self.sb.search('index') - self.assertEqual(results['hits'], 3) - - results = self.sb.search('indexing') - self.assertEqual(results['hits'], 3) + # def test_stemming(self): + # self.sb.update(self.msi, self.sample_objs) + # self.assertEqual(len(self.xapian_search('')), 3) + # + # results = self.sb.search('index') + # self.assertEqual(results['hits'], 3) + # + # results = self.sb.search('indexing') + # self.assertEqual(results['hits'], 3) - def test_more_like_this(self): - self.sb.update(self.msi, self.sample_objs) - self.assertEqual(len(self.xapian_search('')), 3) - - results = self.sb.more_like_this(self.sample_objs[0]) - self.assertEqual(results['hits'], 2) - self.assertEqual([result.pk for result in results['results']], [3, 2]) - - results = self.sb.more_like_this(self.sample_objs[0], additional_query_string='david3') - self.assertEqual(results['hits'], 1) - self.assertEqual([result.pk for result in results['results']], [3]) + # def test_more_like_this(self): + # self.sb.update(self.msi, self.sample_objs) + # self.assertEqual(len(self.xapian_search('')), 3) + # + # results = self.sb.more_like_this(self.sample_objs[0]) + # self.assertEqual(results['hits'], 2) + # self.assertEqual([result.pk for result in results['results']], [3, 2]) + # + # results = self.sb.more_like_this(self.sample_objs[0], additional_query_string='david3') + # self.assertEqual(results['hits'], 1) + # self.assertEqual([result.pk for result in results['results']], [3]) - def test_document_count(self): - self.sb.update(self.msi, self.sample_objs) - self.assertEqual(self.sb.document_count(), 3) + # def test_document_count(self): + # self.sb.update(self.msi, self.sample_objs) + # self.assertEqual(self.sb.document_count(), 3) - def test_delete_index(self): - self.sb.update(self.msi, self.sample_objs) - self.assert_(self.sb.document_count() > 0) - - self.sb.delete_index() - self.assertRaises(InvalidIndexError, self.sb.document_count) + # def test_delete_index(self): + # self.sb.update(self.msi, self.sample_objs) + # self.assert_(self.sb.document_count() > 0) + # + # self.sb.delete_index() + # self.assertRaises(InvalidIndexError, self.sb.document_count) - def test_order_by(self): - self.sb.update(self.msi, self.sample_objs) - - results = self.sb.search('*', sort_by=['pub_date']) - self.assertEqual([result.pk for result in results['results']], [3, 2, 1]) - - results = self.sb.search('*', sort_by=['-pub_date']) - self.assertEqual([result.pk for result in results['results']], [1, 2, 3]) + # def test_order_by(self): + # self.sb.update(self.msi, self.sample_objs) + # + # results = self.sb.search('*', sort_by=['pub_date']) + # self.assertEqual([result.pk for result in results['results']], [3, 2, 1]) + # + # results = self.sb.search('*', sort_by=['-pub_date']) + # self.assertEqual([result.pk for result in results['results']], [1, 2, 3]) + # + # results = self.sb.search('*', sort_by=['id']) + # self.assertEqual([result.pk for result in results['results']], [1, 2, 3]) + # + # results = self.sb.search('*', sort_by=['-id']) + # self.assertEqual([result.pk for result in results['results']], [3, 2, 1]) + # + # results = self.sb.search('*', sort_by=['value']) + # self.assertEqual([result.pk for result in results['results']], [1, 2, 3]) + # + # results = self.sb.search('*', sort_by=['-value']) + # self.assertEqual([result.pk for result in results['results']], [3, 2, 1]) + # + # results = self.sb.search('*', sort_by=['popularity']) + # self.assertEqual([result.pk for result in results['results']], [2, 1, 3]) + # + # results = self.sb.search('*', sort_by=['-popularity']) + # self.assertEqual([result.pk for result in results['results']], [3, 1, 2]) + # + # results = self.sb.search('*', sort_by=['flag', 'id']) + # self.assertEqual([result.pk for result in results['results']], [2, 1, 3]) + # + # results = self.sb.search('*', sort_by=['flag', '-id']) + # self.assertEqual([result.pk for result in results['results']], [2, 3, 1]) - results = self.sb.search('*', sort_by=['id']) - self.assertEqual([result.pk for result in results['results']], [1, 2, 3]) - - results = self.sb.search('*', sort_by=['-id']) - self.assertEqual([result.pk for result in results['results']], [3, 2, 1]) - - results = self.sb.search('*', sort_by=['value']) - self.assertEqual([result.pk for result in results['results']], [1, 2, 3]) - - results = self.sb.search('*', sort_by=['-value']) - self.assertEqual([result.pk for result in results['results']], [3, 2, 1]) - - results = self.sb.search('*', sort_by=['popularity']) - self.assertEqual([result.pk for result in results['results']], [2, 1, 3]) - - results = self.sb.search('*', sort_by=['-popularity']) - self.assertEqual([result.pk for result in results['results']], [3, 1, 2]) - - results = self.sb.search('*', sort_by=['flag', 'id']) - self.assertEqual([result.pk for result in results['results']], [2, 1, 3]) - - results = self.sb.search('*', sort_by=['flag', '-id']) - self.assertEqual([result.pk for result in results['results']], [2, 3, 1]) - - def test_boost(self): - self.sb.update(self.msi, self.sample_objs) - - # TODO: Need a better test case here. Possibly better test data? - results = self.sb.search('*', boost={'true': 2}) - self.assertEqual([result.pk for result in results['results']], [1, 3, 2]) - - results = self.sb.search('*', boost={'true': 1.5}) - self.assertEqual([result.pk for result in results['results']], [1, 3, 2]) + # def test_boost(self): + # self.sb.update(self.msi, self.sample_objs) + # + # # TODO: Need a better test case here. Possibly better test data? + # results = self.sb.search('*', boost={'true': 2}) + # self.assertEqual([result.pk for result in results['results']], [1, 3, 2]) + # + # results = self.sb.search('*', boost={'true': 1.5}) + # self.assertEqual([result.pk for result in results['results']], [1, 3, 2]) def test__marshal_value(self): - self.assertEqual(self.sb._marshal_value('abc'), u'abc') - self.assertEqual(self.sb._marshal_value(1), '000000000001') - self.assertEqual(self.sb._marshal_value(2653), '000000002653') - self.assertEqual(self.sb._marshal_value(25.5), '\xb2`') - self.assertEqual(self.sb._marshal_value([1, 2, 3]), u'[1, 2, 3]') - self.assertEqual(self.sb._marshal_value((1, 2, 3)), u'(1, 2, 3)') - self.assertEqual(self.sb._marshal_value({'a': 1, 'c': 3, 'b': 2}), u"{'a': 1, 'c': 3, 'b': 2}") - self.assertEqual(self.sb._marshal_value(datetime.datetime(2009, 5, 9, 16, 14)), u'20090509161400') - self.assertEqual(self.sb._marshal_value(datetime.datetime(2009, 5, 9, 0, 0)), u'20090509000000') - self.assertEqual(self.sb._marshal_value(datetime.datetime(1899, 5, 18, 0, 0)), u'18990518000000') - self.assertEqual(self.sb._marshal_value(datetime.datetime(2009, 5, 18, 1, 16, 30, 250)), u'20090518011630000250') + self.assertEqual(_marshal_value('abc'), u'abc') + self.assertEqual(_marshal_value(1), '000000000001') + self.assertEqual(_marshal_value(2653), '000000002653') + self.assertEqual(_marshal_value(25.5), '\xb2`') + self.assertEqual(_marshal_value([1, 2, 3]), u'[1, 2, 3]') + self.assertEqual(_marshal_value((1, 2, 3)), u'(1, 2, 3)') + self.assertEqual(_marshal_value({'a': 1, 'c': 3, 'b': 2}), u"{'a': 1, 'c': 3, 'b': 2}") + self.assertEqual(_marshal_value(datetime.datetime(2009, 5, 9, 16, 14)), u'20090509161400') + self.assertEqual(_marshal_value(datetime.datetime(2009, 5, 9, 0, 0)), u'20090509000000') + self.assertEqual(_marshal_value(datetime.datetime(1899, 5, 18, 0, 0)), u'18990518000000') + self.assertEqual(_marshal_value(datetime.datetime(2009, 5, 18, 1, 16, 30, 250)), u'20090518011630000250') def test_build_schema(self): (content_field_name, fields) = self.sb.build_schema(self.site.all_searchfields()) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index 24c984b..1b84c40 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -49,7 +49,7 @@ class XapianSearchQueryTestCase(TestCase): def test_build_query_datetime(self): self.sq.add_filter(SQ(content=datetime.datetime(2009, 5, 8, 11, 28))) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(20090508T112800Z)') + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(20090508112800)') def test_build_query_multiple_words_and(self): self.sq.add_filter(SQ(content='hello')) @@ -100,11 +100,11 @@ class XapianSearchQueryTestCase(TestCase): # def test_build_query_multiple_filter_types(self): # self.sq.add_filter(SQ(content='why')) # self.sq.add_filter(SQ(pub_date__lte='2009-02-10 01:59:00')) - # self.sq.add_filter(SQ(author__gt='daniel')) + # self.sq.add_filter(SQ(author__gt='david')) # self.sq.add_filter(SQ(created__lt='2009-02-12 12:13:00')) # self.sq.add_filter(SQ(title__gte='B')) # self.sq.add_filter(SQ(id__in=[1, 2, 3])) - # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(why AND pub_date:[* TO "2009-02-10 01:59:00"] AND author:{daniel TO *} AND created:{* TO "2009-02-12 12:13:00"} AND title:[B TO *] AND (id:"1" OR id:"2" OR id:"3"))') + # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(why AND pub_date:[* TO "2009-02-10 01:59:00"] AND author:{david TO *} AND created:{* TO "2009-02-12 12:13:00"} AND title:[B TO *] AND (id:"1" OR id:"2" OR id:"3"))') def test_build_query_in_filter_single_words(self): self.sq.add_filter(SQ(content='why')) @@ -126,15 +126,15 @@ class XapianSearchQueryTestCase(TestCase): self.sq.add_filter(~SQ(title__in=["A Famous Paper", "An Infamous Article"])) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((why AND ( AND_NOT ((XTITLEa PHRASE 3 XTITLEfamous PHRASE 3 XTITLEpaper) OR (XTITLEan PHRASE 3 XTITLEinfamous PHRASE 3 XTITLEarticle)))))') - # def test_build_query_in_filter_datetime(self): - # self.sq.add_filter(SQ(content='why')) - # self.sq.add_filter(SQ(pub_date__in=[datetime.datetime(2009, 7, 6, 1, 56, 21)])) - # self.assertEqual(self.sq.build_query(), u'(why AND (pub_date:"2009-07-06T01:56:21Z"))') - # + def test_build_query_in_filter_datetime(self): + self.sq.add_filter(SQ(content='why')) + self.sq.add_filter(SQ(pub_date__in=[datetime.datetime(2009, 7, 6, 1, 56, 21)])) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((why AND XPUB_DATE20090706015621))') + # def test_build_query_wildcard_filter_types(self): # self.sq.add_filter(SQ(content='why')) # self.sq.add_filter(SQ(title__startswith='haystack')) - # self.assertEqual(self.sq.build_query(), u'(why AND title:haystack*)') + # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(why AND XTITLEhaystack*)') def test_clean(self): self.assertEqual(self.sq.clean('hello world'), 'hello world') diff --git a/xapian_backend.py b/xapian_backend.py index f225af9..d684828 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -33,59 +33,6 @@ DOCUMENT_CUSTOM_TERM_PREFIX = 'X' DOCUMENT_CT_TERM_PREFIX = DOCUMENT_CUSTOM_TERM_PREFIX + 'CONTENTTYPE' -class InvalidIndexError(HaystackError): - """Raised when an index can not be opened.""" - pass - - -class XHValueRangeProcessor(xapian.ValueRangeProcessor): - def __init__(self, sb): - self.sb = sb - xapian.ValueRangeProcessor.__init__(self) - - def __call__(self, begin, end): - """ - Construct a tuple for value range processing. - - `begin` -- a string in the format ':[low_range]' - If 'low_range' is omitted, assume the smallest possible value. - `end` -- a string in the the format '[high_range|*]'. If '*', assume - the highest possible value. - - Return a tuple of three strings: (column, low, high) - """ - colon = begin.find(':') - field_name = begin[:colon] - begin = begin[colon + 1:len(begin)] - for field_dict in self.sb.schema: - if field_dict['field_name'] == field_name: - if not begin: - if field_dict['type'] == 'text': - begin = u'a' # TODO: A better way of getting a min text value? - elif field_dict['type'] == 'long': - begin = -sys.maxint - 1 - elif field_dict['type'] == 'float': - begin = float('-inf') - elif field_dict['type'] == 'date' or field_dict['type'] == 'datetime': - begin = u'00010101000000' - elif end == '*': - if field_dict['type'] == 'text': - end = u'z' * 100 # TODO: A better way of getting a max text value? - elif field_dict['type'] == 'long': - end = sys.maxint - elif field_dict['type'] == 'float': - end = float('inf') - elif field_dict['type'] == 'date' or field_dict['type'] == 'datetime': - end = u'99990101000000' - if field_dict['type'] == 'float': - begin = _marshal_value(float(begin)) - end = _marshal_value(float(end)) - elif field_dict['type'] == 'long': - begin = _marshal_value(long(begin)) - end = _marshal_value(long(end)) - return field_dict['column'], str(begin), str(end) - - class XHExpandDecider(xapian.ExpandDecider): def __call__(self, term): """ @@ -116,7 +63,7 @@ class SearchBackend(BaseSearchBackend): your settings. This should point to a location where you would your indexes to reside. """ - def __init__(self, site=None, stemming_language='english'): + def __init__(self, site=None, language='english'): """ Instantiates an instance of `SearchBackend`. @@ -134,7 +81,7 @@ class SearchBackend(BaseSearchBackend): if not os.path.exists(settings.HAYSTACK_XAPIAN_PATH): os.makedirs(settings.HAYSTACK_XAPIAN_PATH) - self.stemmer = xapian.Stem(stemming_language) + self.language = language def update(self, index, iterable): """ @@ -177,7 +124,14 @@ class SearchBackend(BaseSearchBackend): try: for obj in iterable: document = xapian.Document() - term_generator = self._term_generator(database, document) + + term_generator = xapian.TermGenerator() + term_generator.set_database(database) + term_generator.set_stemmer(self.language) + if getattr(settings, 'HAYSTACK_INCLUDE_SPELLING', False) is True: + term_generator.set_flags(xapian.TermGenerator.FLAG_SPELLING) + term_generator.set_document(document) + document_id = DOCUMENT_ID_TERM_PREFIX + get_identifier(obj) data = index.prepare(obj) @@ -231,9 +185,9 @@ class SearchBackend(BaseSearchBackend): """ database = self._database(writable=True) if not models: - query, __unused__ = self._query(database, '*') + query = xapian.Query('') enquire = self._enquire(database, query) - for match in enquire.get_mset(0, self.document_count()): + for match in enquire.get_mset(0, database.get_doccount()): database.delete_document(match.docid) else: for model in models: @@ -326,7 +280,7 @@ class SearchBackend(BaseSearchBackend): 'queries': {}, } if not end_offset: - end_offset = self.document_count() + end_offset = database.get_doccount() matches = enquire.get_mset(start_offset, (end_offset - start_offset)) for match in matches: @@ -364,12 +318,6 @@ class SearchBackend(BaseSearchBackend): if os.path.exists(settings.HAYSTACK_XAPIAN_PATH): shutil.rmtree(settings.HAYSTACK_XAPIAN_PATH) - def document_count(self): - """ - Retrieves the total document count for the search index. - """ - return self._database().get_doccount() - def more_like_this(self, model_instance, additional_query_string=None, start_offset=0, end_offset=None, limit_to_registered_models=True, **kwargs): @@ -408,7 +356,7 @@ class SearchBackend(BaseSearchBackend): enquire = self._enquire(database, query) rset = xapian.RSet() if not end_offset: - end_offset = self.document_count() + end_offset = database.get_doccount() for match in enquire.get_mset(0, end_offset): rset.add_document(match.docid) query = xapian.Query(xapian.Query.OP_OR, @@ -530,6 +478,7 @@ class SearchBackend(BaseSearchBackend): """ facet_dict = {} + # DS_TODO: Improve this algorithm. Currently, runs in O(N^3), ouch. for field in field_facets: facet_list = {} @@ -663,103 +612,13 @@ class SearchBackend(BaseSearchBackend): database.set_metadata('schema', pickle.dumps(self.schema, pickle.HIGHEST_PROTOCOL)) database.set_metadata('content', pickle.dumps(self.content_field_name, pickle.HIGHEST_PROTOCOL)) else: - try: - database = xapian.Database(settings.HAYSTACK_XAPIAN_PATH) - except xapian.DatabaseOpeningError: - raise InvalidIndexError(u'Unable to open index at %s' % settings.HAYSTACK_XAPIAN_PATH) + database = xapian.Database(settings.HAYSTACK_XAPIAN_PATH) self.schema = pickle.loads(database.get_metadata('schema')) self.content_field_name = pickle.loads(database.get_metadata('content')) return database - def _term_generator(self, database, document): - """ - Private method that returns a Xapian.TermGenerator - - Required Argument: - `document` -- The document to be indexed - - Returns a Xapian.TermGenerator instance. If `HAYSTACK_INCLUDE_SPELLING` - is True, then the term generator will have spell-checking enabled. - """ - term_generator = xapian.TermGenerator() - term_generator.set_database(database) - term_generator.set_stemmer(self.stemmer) - if getattr(settings, 'HAYSTACK_INCLUDE_SPELLING', False) is True: - term_generator.set_flags(xapian.TermGenerator.FLAG_SPELLING) - term_generator.set_document(document) - return term_generator - - def _query(self, database, query_string, narrow_queries=None, spelling_query=None): - """ - Private method that takes a query string and returns a xapian.Query. - - Required arguments: - `database` -- The database to query - `query_string` -- The query string to parse - - Optional arguments: - `narrow_queries` -- A list of queries to narrow the query with - `spelling_query` -- An optional query to execute spelling suggestion on - - Returns a xapian.Query instance with prefixes and ranges properly - setup as pulled from the `query_string`. - """ - spelling_suggestion = None - qp = None - - if query_string == '*': - query = xapian.Query('') # Make '*' match everything - else: - qp = self._query_parser(database) - vrp = XHValueRangeProcessor(self) - qp.add_valuerangeprocessor(vrp) - query = qp.parse_query(query_string, self._flags(query_string)) - if getattr(settings, 'HAYSTACK_INCLUDE_SPELLING', False) is True: - if spelling_query: - qp.parse_query(spelling_query, self._flags(spelling_query)) - spelling_suggestion = qp.get_corrected_query_string() - else: - spelling_suggestion = qp.get_corrected_query_string() - - if narrow_queries: - if qp is None: - qp = self._query_parser(database) - subqueries = [ - qp.parse_query( - narrow_query, self._flags(narrow_query) - ) for narrow_query in narrow_queries - ] - query = xapian.Query( - xapian.Query.OP_FILTER, - query, xapian.Query(xapian.Query.OP_AND, subqueries) - ) - - return query, spelling_suggestion - - def _flags(self, query_string): - """ - Private method that returns an appropriate xapian.QueryParser flags - set given a `query_string`. - - Required Arguments: - `query_string` -- The query string to be parsed. - - Returns a xapian.QueryParser flag set (an integer) - """ - flags = xapian.QueryParser.FLAG_PARTIAL \ - | xapian.QueryParser.FLAG_PHRASE \ - | xapian.QueryParser.FLAG_BOOLEAN \ - | xapian.QueryParser.FLAG_LOVEHATE - if '*' in query_string: - flags = flags | xapian.QueryParser.FLAG_WILDCARD - if 'NOT' in query_string.upper(): - flags = flags | xapian.QueryParser.FLAG_PURE_NOT - if getattr(settings, 'HAYSTACK_INCLUDE_SPELLING', False) is True: - flags = flags | xapian.QueryParser.FLAG_SPELLING_CORRECTION - return flags - def _sorter(self, sort_by): """ Private method that takes a list of fields to sort by and returns a @@ -781,29 +640,7 @@ class SearchBackend(BaseSearchBackend): sorter.add(self._value_column(sort_field), reverse) return sorter - - def _query_parser(self, database): - """ - Private method that returns a Xapian.QueryParser instance. - Required arguments: - `database` -- The database to be queried - - The query parser returned will have stemming enabled, a boolean prefix - for `django_ct`, and prefixes for all of the fields in the `self.schema`. - """ - qp = xapian.QueryParser() - qp.set_database(database) - qp.set_stemmer(self.stemmer) - qp.set_stemming_strategy(xapian.QueryParser.STEM_SOME) - qp.add_boolean_prefix('django_ct', DOCUMENT_CT_TERM_PREFIX) - for field_dict in self.schema: - qp.add_prefix( - field_dict['field_name'], - DOCUMENT_CUSTOM_TERM_PREFIX + field_dict['field_name'].upper() - ) - return qp - def _enquire(self, database, query): """ Private method that that returns a Xapian.Enquire instance for use with @@ -1011,6 +848,7 @@ class SearchQuery(BaseSearchQuery): """ query_list = [] for value in value_list: + value = _marshal_value(value) if ' ' in value: query_list.append( xapian.Query( @@ -1087,17 +925,17 @@ def _marshal_value(value): """ if isinstance(value, datetime.datetime): if value.microsecond: - value = u'%04d%02d%02dT%02d%02d%02d%06dZ' % ( + value = u'%04d%02d%02d%02d%02d%02d%06d' % ( value.year, value.month, value.day, value.hour, value.minute, value.second, value.microsecond ) else: - value = u'%04d%02d%02dT%02d%02d%02dZ' % ( + value = u'%04d%02d%02d%02d%02d%02d' % ( value.year, value.month, value.day, value.hour, value.minute, value.second ) elif isinstance(value, datetime.date): - value = u'%04d%02d%02dT000000Z' % (value.year, value.month, value.day) + value = u'%04d%02d%02d000000' % (value.year, value.month, value.day) elif isinstance(value, bool): if value: value = u'true' From 8351f79326cf673081000e7b0e7ed1108e04e4e5 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Wed, 2 Dec 2009 13:10:30 -0500 Subject: [PATCH 76/98] SearchBackend.update is working again --- tests/xapian_tests/tests/xapian_backend.py | 26 +++++++++++----------- xapian_backend.py | 2 +- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_backend.py b/tests/xapian_tests/tests/xapian_backend.py index b1f44f7..d232296 100644 --- a/tests/xapian_tests/tests/xapian_backend.py +++ b/tests/xapian_tests/tests/xapian_backend.py @@ -109,22 +109,22 @@ class XapianSearchBackendTestCase(TestCase): document = match.get_document() app_label, module_name, pk, model_data = pickle.loads(document.get_data()) for key, value in model_data.iteritems(): - model_data[key] = self.sb._marshal_value(value) + model_data[key] = _marshal_value(value) model_data['id'] = u'%s.%s.%d' % (app_label, module_name, pk) document_list.append(model_data) return document_list - # def test_update(self): - # self.sb.update(self.msi, self.sample_objs) - # self.sb.update(self.msi, self.sample_objs) # Duplicates should be updated, not appended -- http://github.com/notanumber/xapian-haystack/issues/#issue/6 - # - # self.assertEqual(len(self.xapian_search('')), 3) - # self.assertEqual([dict(doc) for doc in self.xapian_search('')], [ - # {'flag': u't', 'name': u'david1', 'text': u'Indexed!\n1', 'sites': u"['1', '2', '3']", 'pub_date': u'20090224000000', 'value': u'000000000005', 'id': u'tests.xapianmockmodel.1', 'slug': u'http://example.com/1', 'popularity': '\xca\x84', 'django_id': u'1', 'django_ct': u'tests.xapianmockmodel'}, - # {'flag': u'f', 'name': u'david2', 'text': u'Indexed!\n2', 'sites': u"['2', '4', '6']", 'pub_date': u'20090223000000', 'value': u'000000000010', 'id': u'tests.xapianmockmodel.2', 'slug': u'http://e - # {'flag': u't', 'name': u'david3', 'text': u'Indexed!\n3', 'sites': u"['3', '6', '9']", 'pub_date': u'20090222000000', 'value': u'000000000015', 'id': u'tests.xapianmockmodel.3', 'slug': u'http://example.com/3', 'popularity': '\xcb\x98', 'django_id': u'3', 'django_ct': u'tests.xapianmockmodel'} - # ]) + def test_update(self): + self.sb.update(self.msi, self.sample_objs) + self.sb.update(self.msi, self.sample_objs) # Duplicates should be updated, not appended -- http://github.com/notanumber/xapian-haystack/issues/#issue/6 + + self.assertEqual(len(self.xapian_search('')), 3) + self.assertEqual([dict(doc) for doc in self.xapian_search('')], [ + {'flag': u'true', 'name': u'david1', 'text': u'indexed!\n1', 'sites': u"['1', '2', '3']", 'pub_date': u'20090224000000', 'value': u'000000000005', 'id': u'tests.xapianmockmodel.1', 'slug': u'http://example.com/1', 'popularity': '\xca\x84', 'django_id': u'1', 'django_ct': u'tests.xapianmockmodel'}, + {'flag': u'false', 'name': u'david2', 'text': u'indexed!\n2', 'sites': u"['2', '4', '6']", 'pub_date': u'20090223000000', 'value': u'000000000010', 'id': u'tests.xapianmockmodel.2', 'slug': u'http://example.com/2', 'popularity': '\xb4p', 'django_id': u'2', 'django_ct': u'tests.xapianmockmodel'}, + {'flag': u'true', 'name': u'david3', 'text': u'indexed!\n3', 'sites': u"['3', '6', '9']", 'pub_date': u'20090222000000', 'value': u'000000000015', 'id': u'tests.xapianmockmodel.3', 'slug': u'http://example.com/3', 'popularity': '\xcb\x98', 'django_id': u'3', 'django_ct': u'tests.xapianmockmodel'} + ]) # def test_remove(self): # self.sb.update(self.msi, self.sample_objs) @@ -133,8 +133,8 @@ class XapianSearchBackendTestCase(TestCase): # self.sb.remove(self.sample_objs[0]) # self.assertEqual(len(self.xapian_search('')), 2) # self.assertEqual([dict(doc) for doc in self.xapian_search('')], [ - # {'flag': u'f', 'name': u'david2', 'text': u'Indexed!\n2', 'sites': u"['2', '4', '6']", 'pub_date': u'20090223000000', 'value': u'000000000010', 'id': u'tests.xapianmockmodel.2', 'slug': u'http://e - # {'flag': u't', 'name': u'david3', 'text': u'Indexed!\n3', 'sites': u"['3', '6', '9']", 'pub_date': u'20090222000000', 'value': u'000000000015', 'id': u'tests.xapianmockmodel.3', 'slug': u'http://example.com/3', 'popularity': '\xcb\x98', 'django_id': u'3', 'django_ct': u'tests.xapianmockmodel'} + # {'flag': u'false', 'name': u'david2', 'text': u'Indexed!\n2', 'sites': u"['2', '4', '6']", 'pub_date': u'20090223000000', 'value': u'000000000010', 'id': u'tests.xapianmockmodel.2', 'slug': u'http://example.com/2', 'popularity': '\xb4p', 'django_id': u'2', 'django_ct': u'tests.xapianmockmodel'}, + # {'flag': u'true', 'name': u'david3', 'text': u'Indexed!\n3', 'sites': u"['3', '6', '9']", 'pub_date': u'20090222000000', 'value': u'000000000015', 'id': u'tests.xapianmockmodel.3', 'slug': u'http://example.com/3', 'popularity': '\xcb\x98', 'django_id': u'3', 'django_ct': u'tests.xapianmockmodel'} # ]) # def test_clear(self): diff --git a/xapian_backend.py b/xapian_backend.py index d684828..2e8243d 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -127,7 +127,7 @@ class SearchBackend(BaseSearchBackend): term_generator = xapian.TermGenerator() term_generator.set_database(database) - term_generator.set_stemmer(self.language) + term_generator.set_stemmer(xapian.Stem(self.language)) if getattr(settings, 'HAYSTACK_INCLUDE_SPELLING', False) is True: term_generator.set_flags(xapian.TermGenerator.FLAG_SPELLING) term_generator.set_document(document) From 166f2b2109d905e29b9bda6c90e12c8211713dd8 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Wed, 2 Dec 2009 13:11:57 -0500 Subject: [PATCH 77/98] SearchBackend.remove is also working --- tests/xapian_tests/tests/xapian_backend.py | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_backend.py b/tests/xapian_tests/tests/xapian_backend.py index d232296..2b6493b 100644 --- a/tests/xapian_tests/tests/xapian_backend.py +++ b/tests/xapian_tests/tests/xapian_backend.py @@ -126,16 +126,16 @@ class XapianSearchBackendTestCase(TestCase): {'flag': u'true', 'name': u'david3', 'text': u'indexed!\n3', 'sites': u"['3', '6', '9']", 'pub_date': u'20090222000000', 'value': u'000000000015', 'id': u'tests.xapianmockmodel.3', 'slug': u'http://example.com/3', 'popularity': '\xcb\x98', 'django_id': u'3', 'django_ct': u'tests.xapianmockmodel'} ]) - # def test_remove(self): - # self.sb.update(self.msi, self.sample_objs) - # self.assertEqual(len(self.xapian_search('')), 3) - # - # self.sb.remove(self.sample_objs[0]) - # self.assertEqual(len(self.xapian_search('')), 2) - # self.assertEqual([dict(doc) for doc in self.xapian_search('')], [ - # {'flag': u'false', 'name': u'david2', 'text': u'Indexed!\n2', 'sites': u"['2', '4', '6']", 'pub_date': u'20090223000000', 'value': u'000000000010', 'id': u'tests.xapianmockmodel.2', 'slug': u'http://example.com/2', 'popularity': '\xb4p', 'django_id': u'2', 'django_ct': u'tests.xapianmockmodel'}, - # {'flag': u'true', 'name': u'david3', 'text': u'Indexed!\n3', 'sites': u"['3', '6', '9']", 'pub_date': u'20090222000000', 'value': u'000000000015', 'id': u'tests.xapianmockmodel.3', 'slug': u'http://example.com/3', 'popularity': '\xcb\x98', 'django_id': u'3', 'django_ct': u'tests.xapianmockmodel'} - # ]) + def test_remove(self): + self.sb.update(self.msi, self.sample_objs) + self.assertEqual(len(self.xapian_search('')), 3) + + self.sb.remove(self.sample_objs[0]) + self.assertEqual(len(self.xapian_search('')), 2) + self.assertEqual([dict(doc) for doc in self.xapian_search('')], [ + {'flag': u'false', 'name': u'david2', 'text': u'indexed!\n2', 'sites': u"['2', '4', '6']", 'pub_date': u'20090223000000', 'value': u'000000000010', 'id': u'tests.xapianmockmodel.2', 'slug': u'http://example.com/2', 'popularity': '\xb4p', 'django_id': u'2', 'django_ct': u'tests.xapianmockmodel'}, + {'flag': u'true', 'name': u'david3', 'text': u'indexed!\n3', 'sites': u"['3', '6', '9']", 'pub_date': u'20090222000000', 'value': u'000000000015', 'id': u'tests.xapianmockmodel.3', 'slug': u'http://example.com/3', 'popularity': '\xcb\x98', 'django_id': u'3', 'django_ct': u'tests.xapianmockmodel'} + ]) # def test_clear(self): # self.sb.update(self.msi, self.sample_objs) From 8b88e544b3df5748dec0484e817598621053fe4d Mon Sep 17 00:00:00 2001 From: David Sauve Date: Wed, 2 Dec 2009 13:12:40 -0500 Subject: [PATCH 78/98] SearchBackend.clear confirmed working --- tests/xapian_tests/tests/xapian_backend.py | 42 +++++++++++----------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_backend.py b/tests/xapian_tests/tests/xapian_backend.py index 2b6493b..e21685e 100644 --- a/tests/xapian_tests/tests/xapian_backend.py +++ b/tests/xapian_tests/tests/xapian_backend.py @@ -137,27 +137,27 @@ class XapianSearchBackendTestCase(TestCase): {'flag': u'true', 'name': u'david3', 'text': u'indexed!\n3', 'sites': u"['3', '6', '9']", 'pub_date': u'20090222000000', 'value': u'000000000015', 'id': u'tests.xapianmockmodel.3', 'slug': u'http://example.com/3', 'popularity': '\xcb\x98', 'django_id': u'3', 'django_ct': u'tests.xapianmockmodel'} ]) - # def test_clear(self): - # self.sb.update(self.msi, self.sample_objs) - # self.assertEqual(len(self.xapian_search('')), 3) - # - # self.sb.clear() - # self.assertEqual(len(self.xapian_search('')), 0) - # - # self.sb.update(self.msi, self.sample_objs) - # self.assertEqual(len(self.xapian_search('')), 3) - # - # self.sb.clear([AnotherMockModel]) - # self.assertEqual(len(self.xapian_search('')), 3) - # - # self.sb.clear([XapianMockModel]) - # self.assertEqual(len(self.xapian_search('')), 0) - # - # self.sb.update(self.msi, self.sample_objs) - # self.assertEqual(len(self.xapian_search('')), 3) - # - # self.sb.clear([AnotherMockModel, XapianMockModel]) - # self.assertEqual(len(self.xapian_search('')), 0) + def test_clear(self): + self.sb.update(self.msi, self.sample_objs) + self.assertEqual(len(self.xapian_search('')), 3) + + self.sb.clear() + self.assertEqual(len(self.xapian_search('')), 0) + + self.sb.update(self.msi, self.sample_objs) + self.assertEqual(len(self.xapian_search('')), 3) + + self.sb.clear([AnotherMockModel]) + self.assertEqual(len(self.xapian_search('')), 3) + + self.sb.clear([XapianMockModel]) + self.assertEqual(len(self.xapian_search('')), 0) + + self.sb.update(self.msi, self.sample_objs) + self.assertEqual(len(self.xapian_search('')), 3) + + self.sb.clear([AnotherMockModel, XapianMockModel]) + self.assertEqual(len(self.xapian_search('')), 0) # def test_search(self): # self.sb.update(self.msi, self.sample_objs) From 6ffeb960903fec1d94178f3a4c85fa8644c2b4fb Mon Sep 17 00:00:00 2001 From: David Sauve Date: Wed, 2 Dec 2009 13:35:00 -0500 Subject: [PATCH 79/98] Removed SearchBackend.delete_index. Is not part of the API. --- tests/xapian_tests/tests/xapian_backend.py | 21 +++++++-------------- xapian_backend.py | 13 ++----------- 2 files changed, 9 insertions(+), 25 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_backend.py b/tests/xapian_tests/tests/xapian_backend.py index e21685e..457f14f 100644 --- a/tests/xapian_tests/tests/xapian_backend.py +++ b/tests/xapian_tests/tests/xapian_backend.py @@ -8,7 +8,6 @@ import xapian from django.conf import settings from django.db import models -from django.utils.encoding import force_unicode from django.test import TestCase from haystack import indexes, sites @@ -117,7 +116,6 @@ class XapianSearchBackendTestCase(TestCase): def test_update(self): self.sb.update(self.msi, self.sample_objs) - self.sb.update(self.msi, self.sample_objs) # Duplicates should be updated, not appended -- http://github.com/notanumber/xapian-haystack/issues/#issue/6 self.assertEqual(len(self.xapian_search('')), 3) self.assertEqual([dict(doc) for doc in self.xapian_search('')], [ @@ -126,6 +124,12 @@ class XapianSearchBackendTestCase(TestCase): {'flag': u'true', 'name': u'david3', 'text': u'indexed!\n3', 'sites': u"['3', '6', '9']", 'pub_date': u'20090222000000', 'value': u'000000000015', 'id': u'tests.xapianmockmodel.3', 'slug': u'http://example.com/3', 'popularity': '\xcb\x98', 'django_id': u'3', 'django_ct': u'tests.xapianmockmodel'} ]) + def test_duplicate_update(self): + self.sb.update(self.msi, self.sample_objs) + self.sb.update(self.msi, self.sample_objs) # Duplicates should be updated, not appended -- http://github.com/notanumber/xapian-haystack/issues/#issue/6 + + self.assertEqual(len(self.xapian_search('')), 3) + def test_remove(self): self.sb.update(self.msi, self.sample_objs) self.assertEqual(len(self.xapian_search('')), 3) @@ -295,18 +299,7 @@ class XapianSearchBackendTestCase(TestCase): # results = self.sb.more_like_this(self.sample_objs[0], additional_query_string='david3') # self.assertEqual(results['hits'], 1) # self.assertEqual([result.pk for result in results['results']], [3]) - - # def test_document_count(self): - # self.sb.update(self.msi, self.sample_objs) - # self.assertEqual(self.sb.document_count(), 3) - - # def test_delete_index(self): - # self.sb.update(self.msi, self.sample_objs) - # self.assert_(self.sb.document_count() > 0) - # - # self.sb.delete_index() - # self.assertRaises(InvalidIndexError, self.sb.document_count) - + # def test_order_by(self): # self.sb.update(self.msi, self.sample_objs) # diff --git a/xapian_backend.py b/xapian_backend.py index 2e8243d..eb9acff 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -17,7 +17,7 @@ from django.core.exceptions import ImproperlyConfigured from django.utils.encoding import smart_unicode, force_unicode from haystack.backends import BaseSearchBackend, BaseSearchQuery, SearchNode, log_query -from haystack.exceptions import MissingDependency, HaystackError +from haystack.exceptions import MissingDependency from haystack.fields import DateField, DateTimeField, IntegerField, FloatField, BooleanField, MultiValueField from haystack.models import SearchResult from haystack.utils import get_identifier @@ -309,15 +309,6 @@ class SearchBackend(BaseSearchBackend): 'spelling_suggestion': spelling_suggestion, } - def delete_index(self): - """ - Delete the index. - - This removes all indexes files and the `HAYSTACK_XAPIAN_PATH` folder. - """ - if os.path.exists(settings.HAYSTACK_XAPIAN_PATH): - shutil.rmtree(settings.HAYSTACK_XAPIAN_PATH) - def more_like_this(self, model_instance, additional_query_string=None, start_offset=0, end_offset=None, limit_to_registered_models=True, **kwargs): @@ -613,7 +604,7 @@ class SearchBackend(BaseSearchBackend): database.set_metadata('content', pickle.dumps(self.content_field_name, pickle.HIGHEST_PROTOCOL)) else: database = xapian.Database(settings.HAYSTACK_XAPIAN_PATH) - + self.schema = pickle.loads(database.get_metadata('schema')) self.content_field_name = pickle.loads(database.get_metadata('content')) From c2e33da295464ebdebb266c076829c17c046284d Mon Sep 17 00:00:00 2001 From: David Sauve Date: Wed, 2 Dec 2009 15:05:53 -0500 Subject: [PATCH 80/98] Removed a bunch of search tests that were testing various query_string combinations. These are no longer relevant. --- tests/xapian_tests/tests/xapian_backend.py | 35 +++----- xapian_backend.py | 97 +++++++++------------- 2 files changed, 52 insertions(+), 80 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_backend.py b/tests/xapian_tests/tests/xapian_backend.py index 457f14f..1dd684f 100644 --- a/tests/xapian_tests/tests/xapian_backend.py +++ b/tests/xapian_tests/tests/xapian_backend.py @@ -163,30 +163,17 @@ class XapianSearchBackendTestCase(TestCase): self.sb.clear([AnotherMockModel, XapianMockModel]) self.assertEqual(len(self.xapian_search('')), 0) - # def test_search(self): - # self.sb.update(self.msi, self.sample_objs) - # self.assertEqual(len(self.xapian_search('')), 3) - # - # # Empty query - # self.assertEqual(self.sb.search(''), {'hits': 0, 'results': []}) - # - # # Wildcard -- All - # self.assertEqual(self.sb.search('*')['hits'], 3) - # self.assertEqual([result.pk for result in self.sb.search('*')['results']], [1, 2, 3]) - # - # # Exact match - # self.assertEqual([result.pk for result in self.sb.search('name:david2')['results']], [2]) - # self.assertEqual([result.pk for result in self.sb.search('value:10')['results']], [2]) - # self.assertEqual([result.pk for result in self.sb.search('flag:false')['results']], [2]) - # self.assertEqual([result.pk for result in self.sb.search('popularity:35.5')['results']], [2]) - # - # # NOT operator - # self.assertEqual([result.pk for result in self.sb.search('NOT name:david1')['results']], [2, 3]) - # self.assertEqual([result.pk for result in self.sb.search('NOT name:david1 AND index')['results']], [2, 3]) - # self.assertEqual([result.pk for result in self.sb.search('index NOT name:david1')['results']], [2, 3]) - # self.assertEqual([result.pk for result in self.sb.search('index NOT name:david1 NOT name:david2')['results']], [3]) - # self.assertEqual([result.pk for result in self.sb.search('NOT name:david1 NOT name:david2')['results']], [3]) - # + def test_search(self): + self.sb.update(self.msi, self.sample_objs) + self.assertEqual(len(self.xapian_search('')), 3) + + # Empty query + self.assertEqual(self.sb.search(xapian.Query()), {'hits': 0, 'results': []}) + + # Wildcard -- All + self.assertEqual(self.sb.search(xapian.Query(''))['hits'], 3) + self.assertEqual([result.pk for result in self.sb.search(xapian.Query(''))['results']], [1, 2, 3]) + # # Ranges # self.assertEqual([result.pk for result in self.sb.search('index name:david2..david3')['results']], [2, 3]) # self.assertEqual([result.pk for result in self.sb.search('index name:..david2')['results']], [1, 2]) diff --git a/xapian_backend.py b/xapian_backend.py index eb9acff..303a9b6 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -186,7 +186,8 @@ class SearchBackend(BaseSearchBackend): database = self._database(writable=True) if not models: query = xapian.Query('') - enquire = self._enquire(database, query) + enquire = xapian.Enquire(database) + enquire.set_query(query) for match in enquire.get_mset(0, database.get_doccount()): database.delete_document(match.docid) else: @@ -246,31 +247,44 @@ class SearchBackend(BaseSearchBackend): and any suggestions for spell correction will be returned as well as the results. """ - if not query: + if xapian.Query.empty(query): return { 'results': [], 'hits': 0, } - if limit_to_registered_models: - if narrow_queries is None: - narrow_queries = set() - - registered_models = self.build_registered_models_list() - - if len(registered_models) > 0: - narrow_queries.add( - ' '.join(['django_ct:%s' % model for model in registered_models]) - ) + # if limit_to_registered_models: + # if narrow_queries is None: + # narrow_queries = set() + # + # registered_models = self.build_registered_models_list() + # + # if len(registered_models) > 0: + # narrow_queries.add( + # ' '.join(['django_ct:%s' % model for model in registered_models]) + # ) database = self._database() - query, spelling_suggestion = self._query( - database, query_string, narrow_queries, spelling_query - ) - enquire = self._enquire(database, query) + + # query, spelling_suggestion = self._query( + # database, query_string, narrow_queries, spelling_query + # ) + spelling_suggestion = '' + + enquire = xapian.Enquire(database) + enquire.set_query(query) if sort_by: - sorter = self._sorter(sort_by) + sorter = xapian.MultiValueSorter() + + for sort_field in sort_by: + if sort_field.startswith('-'): + reverse = True + sort_field = sort_field[1:] # Strip the '-' + else: + reverse = False # Reverse is inverted in Xapian -- http://trac.xapian.org/ticket/311 + sorter.add(self._value_column(sort_field), reverse) + enquire.set_sort_by_key_then_relevance(sorter, True) results = [] @@ -279,8 +293,10 @@ class SearchBackend(BaseSearchBackend): 'dates': {}, 'queries': {}, } + if not end_offset: end_offset = database.get_doccount() + matches = enquire.get_mset(start_offset, (end_offset - start_offset)) for match in matches: @@ -343,13 +359,20 @@ class SearchBackend(BaseSearchBackend): Finally, processes the resulting matches and returns. """ database = self._database() + query = xapian.Query(DOCUMENT_ID_TERM_PREFIX + get_identifier(model_instance)) - enquire = self._enquire(database, query) + + enquire = xapian.Enquire(database) + enquire.set_query(query) + rset = xapian.RSet() + if not end_offset: end_offset = database.get_doccount() + for match in enquire.get_mset(0, end_offset): rset.add_document(match.docid) + query = xapian.Query(xapian.Query.OP_OR, [expand.term for expand in enquire.get_eset(match.document.termlist_count(), rset, XHExpandDecider())] ) @@ -609,45 +632,7 @@ class SearchBackend(BaseSearchBackend): self.content_field_name = pickle.loads(database.get_metadata('content')) return database - - def _sorter(self, sort_by): - """ - Private method that takes a list of fields to sort by and returns a - xapian.MultiValueSorter - Required Arguments: - `sort_by` -- A list of fields to sort by - - Returns a xapian.MultiValueSorter instance - """ - sorter = xapian.MultiValueSorter() - - for sort_field in sort_by: - if sort_field.startswith('-'): - reverse = True - sort_field = sort_field[1:] # Strip the '-' - else: - reverse = False # Reverse is inverted in Xapian -- http://trac.xapian.org/ticket/311 - sorter.add(self._value_column(sort_field), reverse) - - return sorter - - def _enquire(self, database, query): - """ - Private method that that returns a Xapian.Enquire instance for use with - the specifed `query`. - - Required Arguments: - `query` -- The query to run - - Returns a xapian.Enquire instance - """ - enquire = xapian.Enquire(database) - enquire.set_query(query) - enquire.set_docid_order(enquire.ASCENDING) - - return enquire - def _value_column(self, field): """ Private method that returns the column value slot in the database From 4bff8c9376ea4e3a7a2225f3545e89f19d2d055a Mon Sep 17 00:00:00 2001 From: David Sauve Date: Thu, 3 Dec 2009 09:38:49 -0500 Subject: [PATCH 81/98] Split marshalling into two methods: marshal_term and marshal_value as they should be done differently --- tests/xapian_settings.py | 2 +- tests/xapian_tests/__init__.py | 2 +- tests/xapian_tests/models.py | 2 +- tests/xapian_tests/tests/__init__.py | 2 +- tests/xapian_tests/tests/xapian_backend.py | 44 +++---- tests/xapian_tests/tests/xapian_query.py | 10 +- xapian_backend.py | 134 +++++++++++++-------- 7 files changed, 108 insertions(+), 88 deletions(-) mode change 100644 => 100755 tests/xapian_settings.py diff --git a/tests/xapian_settings.py b/tests/xapian_settings.py old mode 100644 new mode 100755 index 6e61cd7..71eb41b --- a/tests/xapian_settings.py +++ b/tests/xapian_settings.py @@ -1,4 +1,4 @@ -# Copyright (C) 2009 David Sauve, Trapeze +# Copyright (C) 2009 David Sauve, Trapeze. All rights reserved. import os from settings import * diff --git a/tests/xapian_tests/__init__.py b/tests/xapian_tests/__init__.py index 07260c5..59d7bea 100644 --- a/tests/xapian_tests/__init__.py +++ b/tests/xapian_tests/__init__.py @@ -1 +1 @@ -# Copyright (C) 2009 David Sauve, Trapeze \ No newline at end of file +# Copyright (C) 2009 David Sauve, Trapeze. All rights reserved. \ No newline at end of file diff --git a/tests/xapian_tests/models.py b/tests/xapian_tests/models.py index 07260c5..59d7bea 100644 --- a/tests/xapian_tests/models.py +++ b/tests/xapian_tests/models.py @@ -1 +1 @@ -# Copyright (C) 2009 David Sauve, Trapeze \ No newline at end of file +# Copyright (C) 2009 David Sauve, Trapeze. All rights reserved. \ No newline at end of file diff --git a/tests/xapian_tests/tests/__init__.py b/tests/xapian_tests/tests/__init__.py index 51a6a8d..1f6c8ea 100644 --- a/tests/xapian_tests/tests/__init__.py +++ b/tests/xapian_tests/tests/__init__.py @@ -1,4 +1,4 @@ -# Copyright (C) 2009 David Sauve, Trapeze +# Copyright (C) 2009 David Sauve, Trapeze. All rights reserved. import warnings diff --git a/tests/xapian_tests/tests/xapian_backend.py b/tests/xapian_tests/tests/xapian_backend.py index 1dd684f..86f9af0 100644 --- a/tests/xapian_tests/tests/xapian_backend.py +++ b/tests/xapian_tests/tests/xapian_backend.py @@ -1,4 +1,4 @@ -# Copyright (C) 2009 David Sauve, Trapeze +# Copyright (C) 2009 David Sauve, Trapeze. All rights reserved. import cPickle as pickle import datetime @@ -114,14 +114,21 @@ class XapianSearchBackendTestCase(TestCase): return document_list + def silly_test(self): + + self.sb.update(self.msi, self.sample_objs) + + self.assertEqual(len(self.xapian_search('indexed')), 3) + self.assertEqual(len(self.xapian_search('Indexed')), 3) + def test_update(self): self.sb.update(self.msi, self.sample_objs) self.assertEqual(len(self.xapian_search('')), 3) self.assertEqual([dict(doc) for doc in self.xapian_search('')], [ - {'flag': u'true', 'name': u'david1', 'text': u'indexed!\n1', 'sites': u"['1', '2', '3']", 'pub_date': u'20090224000000', 'value': u'000000000005', 'id': u'tests.xapianmockmodel.1', 'slug': u'http://example.com/1', 'popularity': '\xca\x84', 'django_id': u'1', 'django_ct': u'tests.xapianmockmodel'}, - {'flag': u'false', 'name': u'david2', 'text': u'indexed!\n2', 'sites': u"['2', '4', '6']", 'pub_date': u'20090223000000', 'value': u'000000000010', 'id': u'tests.xapianmockmodel.2', 'slug': u'http://example.com/2', 'popularity': '\xb4p', 'django_id': u'2', 'django_ct': u'tests.xapianmockmodel'}, - {'flag': u'true', 'name': u'david3', 'text': u'indexed!\n3', 'sites': u"['3', '6', '9']", 'pub_date': u'20090222000000', 'value': u'000000000015', 'id': u'tests.xapianmockmodel.3', 'slug': u'http://example.com/3', 'popularity': '\xcb\x98', 'django_id': u'3', 'django_ct': u'tests.xapianmockmodel'} + {'flag': u't', 'name': u'david1', 'text': u'indexed!\n1', 'sites': u"['1', '2', '3']", 'pub_date': u'20090224000000', 'value': u'000000000005', 'id': u'tests.xapianmockmodel.1', 'slug': u'http://example.com/1', 'popularity': '\xca\x84', 'django_id': u'1', 'django_ct': u'tests.xapianmockmodel'}, + {'flag': u'f', 'name': u'david2', 'text': u'indexed!\n2', 'sites': u"['2', '4', '6']", 'pub_date': u'20090223000000', 'value': u'000000000010', 'id': u'tests.xapianmockmodel.2', 'slug': u'http://example.com/2', 'popularity': '\xb4p', 'django_id': u'2', 'django_ct': u'tests.xapianmockmodel'}, + {'flag': u't', 'name': u'david3', 'text': u'indexed!\n3', 'sites': u"['3', '6', '9']", 'pub_date': u'20090222000000', 'value': u'000000000015', 'id': u'tests.xapianmockmodel.3', 'slug': u'http://example.com/3', 'popularity': '\xcb\x98', 'django_id': u'3', 'django_ct': u'tests.xapianmockmodel'} ]) def test_duplicate_update(self): @@ -137,8 +144,8 @@ class XapianSearchBackendTestCase(TestCase): self.sb.remove(self.sample_objs[0]) self.assertEqual(len(self.xapian_search('')), 2) self.assertEqual([dict(doc) for doc in self.xapian_search('')], [ - {'flag': u'false', 'name': u'david2', 'text': u'indexed!\n2', 'sites': u"['2', '4', '6']", 'pub_date': u'20090223000000', 'value': u'000000000010', 'id': u'tests.xapianmockmodel.2', 'slug': u'http://example.com/2', 'popularity': '\xb4p', 'django_id': u'2', 'django_ct': u'tests.xapianmockmodel'}, - {'flag': u'true', 'name': u'david3', 'text': u'indexed!\n3', 'sites': u"['3', '6', '9']", 'pub_date': u'20090222000000', 'value': u'000000000015', 'id': u'tests.xapianmockmodel.3', 'slug': u'http://example.com/3', 'popularity': '\xcb\x98', 'django_id': u'3', 'django_ct': u'tests.xapianmockmodel'} + {'flag': u'f', 'name': u'david2', 'text': u'indexed!\n2', 'sites': u"['2', '4', '6']", 'pub_date': u'20090223000000', 'value': u'000000000010', 'id': u'tests.xapianmockmodel.2', 'slug': u'http://example.com/2', 'popularity': '\xb4p', 'django_id': u'2', 'django_ct': u'tests.xapianmockmodel'}, + {'flag': u't', 'name': u'david3', 'text': u'indexed!\n3', 'sites': u"['3', '6', '9']", 'pub_date': u'20090222000000', 'value': u'000000000015', 'id': u'tests.xapianmockmodel.3', 'slug': u'http://example.com/3', 'popularity': '\xcb\x98', 'django_id': u'3', 'django_ct': u'tests.xapianmockmodel'} ]) def test_clear(self): @@ -174,19 +181,6 @@ class XapianSearchBackendTestCase(TestCase): self.assertEqual(self.sb.search(xapian.Query(''))['hits'], 3) self.assertEqual([result.pk for result in self.sb.search(xapian.Query(''))['results']], [1, 2, 3]) - # # Ranges - # self.assertEqual([result.pk for result in self.sb.search('index name:david2..david3')['results']], [2, 3]) - # self.assertEqual([result.pk for result in self.sb.search('index name:..david2')['results']], [1, 2]) - # self.assertEqual([result.pk for result in self.sb.search('index name:david2..*')['results']], [2, 3]) - # self.assertEqual([result.pk for result in self.sb.search('index pub_date:20090222000000..20090223000000')['results']], [2, 3]) - # self.assertEqual([result.pk for result in self.sb.search('index pub_date:..20090223000000')['results']], [2, 3]) - # self.assertEqual([result.pk for result in self.sb.search('index pub_date:20090223000000..*')['results']], [1, 2]) - # self.assertEqual([result.pk for result in self.sb.search('index value:10..15')['results']], [2, 3]) - # self.assertEqual([result.pk for result in self.sb.search('index value:..10')['results']], [1, 2]) - # self.assertEqual([result.pk for result in self.sb.search('index value:10..*')['results']], [2, 3]) - # self.assertEqual([result.pk for result in self.sb.search('index popularity:..100.0')['results']], [2]) - # self.assertEqual([result.pk for result in self.sb.search('index popularity:100.0..*')['results']], [1, 3]) - # def test_field_facets(self): # self.sb.update(self.msi, self.sample_objs) # self.assertEqual(len(self.xapian_search('')), 3) @@ -264,17 +258,7 @@ class XapianSearchBackendTestCase(TestCase): # # self.assertEqual(self.sb.search('indx')['hits'], 0) # self.assertEqual(self.sb.search('indx', spelling_query='indexy')['spelling_suggestion'], 'indexed') - - # def test_stemming(self): - # self.sb.update(self.msi, self.sample_objs) - # self.assertEqual(len(self.xapian_search('')), 3) - # - # results = self.sb.search('index') - # self.assertEqual(results['hits'], 3) - # - # results = self.sb.search('indexing') - # self.assertEqual(results['hits'], 3) - + # def test_more_like_this(self): # self.sb.update(self.msi, self.sample_objs) # self.assertEqual(len(self.xapian_search('')), 3) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index 1b84c40..7ceed88 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -1,4 +1,4 @@ -# Copyright (C) 2009 David Sauve, Trapeze +# Copyright (C) 2009 David Sauve, Trapeze. All rights reserved. import datetime import os @@ -51,6 +51,10 @@ class XapianSearchQueryTestCase(TestCase): self.sq.add_filter(SQ(content=datetime.datetime(2009, 5, 8, 11, 28))) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(20090508112800)') + def test_build_query_float(self): + self.sq.add_filter(SQ(content=25.52)) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(25.52)') + def test_build_query_multiple_words_and(self): self.sq.add_filter(SQ(content='hello')) self.sq.add_filter(SQ(content='world')) @@ -136,6 +140,10 @@ class XapianSearchQueryTestCase(TestCase): # self.sq.add_filter(SQ(title__startswith='haystack')) # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(why AND XTITLEhaystack*)') + # def test_stem_single_word(self): + # self.sq.add_filter(SQ(content='testing')) + # self.assertEqual(self.sq.build_query().get_description(), 'Xapian.Query(Ztest)') + # def test_clean(self): self.assertEqual(self.sq.clean('hello world'), 'hello world') self.assertEqual(self.sq.clean('hello AND world'), 'hello AND world') diff --git a/xapian_backend.py b/xapian_backend.py index 303a9b6..3c7c5b3 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -682,6 +682,8 @@ class SearchQuery(BaseSearchQuery): self.backend = backend or SearchBackend() def build_query(self): + # DS_TODO: How does stemming work with this new refactor? + if not self.query_filter: query = xapian.Query('') else: @@ -729,17 +731,19 @@ class SearchQuery(BaseSearchQuery): ) ) else: - expression, value = child + expression, term = child field, filter_type = search_node.split_expression(expression) - if not isinstance(value, (list, tuple)): - value = _marshal_value(value) + if not isinstance(term, (list, tuple)): + term = _marshal_term(term) + else: + term = [_marshal_term(t) for t in term] if field == 'content': - query_list.append(self._content_field(value, is_not)) + query_list.append(self._content_field(term, is_not)) else: if filter_type == 'exact': - query_list.append(self._filter_exact(value, field, is_not)) + query_list.append(self._filter_exact(term, field, is_not)) elif filter_type == 'gt': pass elif filter_type == 'gte': @@ -751,71 +755,71 @@ class SearchQuery(BaseSearchQuery): elif filter_type == 'startswith': pass elif filter_type == 'in': - query_list.append(self._filter_in(value, field, is_not)) + query_list.append(self._filter_in(term, field, is_not)) if search_node.connector == 'OR': return xapian.Query(xapian.Query.OP_OR, query_list) else: return xapian.Query(xapian.Query.OP_AND, query_list) - def _content_field(self, value, is_not): + def _content_field(self, term, is_not): """ Private method that returns a xapian.Query that searches for `value` in all fields. Required arguments: - ``value`` -- The value to search for + ``term`` -- The term to search for ``is_not`` -- Invert the search results Returns: A xapian.Query """ - if ' ' in value: + if ' ' in term: if is_not: return xapian.Query( - xapian.Query.OP_AND_NOT, self._all_query(), self._phrase_query(value.split()) + xapian.Query.OP_AND_NOT, self._all_query(), self._phrase_query(term.split()) ) else: - return self._phrase_query(value.split()) + return self._phrase_query(term.split()) else: if is_not: - return xapian.Query(xapian.Query.OP_AND_NOT, self._all_query(), self._term_query(value)) + return xapian.Query(xapian.Query.OP_AND_NOT, self._all_query(), self._term_query(term)) else: - return self._term_query(value) + return self._term_query(term) - def _filter_exact(self, value, field, is_not): + def _filter_exact(self, term, field, is_not): """ - Private method that returns a xapian.Query that searches for `value` + Private method that returns a xapian.Query that searches for `term` in a specified `field`. Required arguments: - ``value`` -- The value to search for + ``term`` -- The term to search for ``field`` -- The field to search ``is_not`` -- Invert the search results Returns: A xapian.Query """ - if ' ' in value: + if ' ' in term: if is_not: return xapian.Query( - xapian.Query.OP_AND_NOT, self._all_query(), self._phrase_query(value.split(), field) + xapian.Query.OP_AND_NOT, self._all_query(), self._phrase_query(term.split(), field) ) else: - return self._phrase_query(value.split(), field) + return self._phrase_query(term.split(), field) else: if is_not: - return xapian.Query(xapian.Query.OP_AND_NOT, self._all_query(), self._term_query(value, field)) + return xapian.Query(xapian.Query.OP_AND_NOT, self._all_query(), self._term_query(term, field)) else: - return self._term_query(value, field) + return self._term_query(term, field) - def _filter_in(self, value_list, field, is_not): + def _filter_in(self, term_list, field, is_not): """ - Private method that returns a xapian.Query that searches for any value + Private method that returns a xapian.Query that searches for any term of `value_list` in a specified `field`. Required arguments: - ``value_list`` -- The values to search for + ``term_list`` -- The terms to search for ``field`` -- The field to search ``is_not`` -- Invert the search results @@ -823,18 +827,17 @@ class SearchQuery(BaseSearchQuery): A xapian.Query """ query_list = [] - for value in value_list: - value = _marshal_value(value) - if ' ' in value: + for term in term_list: + if ' ' in term: query_list.append( xapian.Query( - xapian.Query.OP_OR, self._phrase_query(value.split(), field) + xapian.Query.OP_OR, self._phrase_query(term.split(), field) ) ) else: query_list.append( xapian.Query( - xapian.Query.OP_OR, self._term_query(value, field) + xapian.Query.OP_OR, self._term_query(term, field) ) ) if is_not: @@ -851,13 +854,13 @@ class SearchQuery(BaseSearchQuery): """ return xapian.Query('') - def _term_query(self, value, field=None): + def _term_query(self, term, field=None): """ Private method that returns a term based xapian.Query that searches - for term `value`. + for `term`. Required arguments: - ``value`` -- The value to search for + ``term`` -- The term to search for ``field`` -- The field to search (If `None`, all fields) Returns: @@ -865,19 +868,19 @@ class SearchQuery(BaseSearchQuery): """ if field: return xapian.Query('%s%s%s' % ( - DOCUMENT_CUSTOM_TERM_PREFIX, field.upper(), _marshal_value(value) + DOCUMENT_CUSTOM_TERM_PREFIX, field.upper(), term ) ) else: - return xapian.Query(value) + return xapian.Query(term) - def _phrase_query(self, value_list, field=None): + def _phrase_query(self, term_list, field=None): """ Private method that returns a phrase based xapian.Query that searches - for terms in `value_list. + for terms in `term_list. Required arguments: - ``value_list`` -- The values to search for + ``term_list`` -- The terms to search for ``field`` -- The field to search (If `None`, all fields) Returns: @@ -887,12 +890,12 @@ class SearchQuery(BaseSearchQuery): return xapian.Query( xapian.Query.OP_PHRASE, [ '%s%s%s' % ( - DOCUMENT_CUSTOM_TERM_PREFIX, field.upper(), _marshal_value(value) - ) for value in value_list + DOCUMENT_CUSTOM_TERM_PREFIX, field.upper(), term + ) for term in term_list ] ) else: - return xapian.Query(xapian.Query.OP_PHRASE, value_list) + return xapian.Query(xapian.Query.OP_PHRASE, term_list) def _marshal_value(value): @@ -900,23 +903,14 @@ def _marshal_value(value): Private utility method that converts Python values to a string for Xapian values. """ if isinstance(value, datetime.datetime): - if value.microsecond: - value = u'%04d%02d%02d%02d%02d%02d%06d' % ( - value.year, value.month, value.day, value.hour, - value.minute, value.second, value.microsecond - ) - else: - value = u'%04d%02d%02d%02d%02d%02d' % ( - value.year, value.month, value.day, value.hour, - value.minute, value.second - ) + value = _marshal_datetime(value) elif isinstance(value, datetime.date): - value = u'%04d%02d%02d000000' % (value.year, value.month, value.day) + value = _marshal_date(value) elif isinstance(value, bool): if value: - value = u'true' + value = u't' else: - value = u'false' + value = u'f' elif isinstance(value, float): value = xapian.sortable_serialise(value) elif isinstance(value, (int, long)): @@ -925,3 +919,37 @@ def _marshal_value(value): value = force_unicode(value).lower() return value + +def _marshal_term(term): + """ + Private utility method that converts Python terms to a string for Xapian terms. + """ + if isinstance(term, datetime.datetime): + term = _marshal_datetime(term) + elif isinstance(term, datetime.date): + term = _marshal_date(term) + elif isinstance(term, bool): + if term: + term = u'true' + else: + term = u'false' + else: + term = force_unicode(term).lower() + return term + + +def _marshal_date(d): + return u'%04d%02d%02d000000' % (d.year, d.month, d.day) + + +def _marshal_datetime(dt): + if dt.microsecond: + return u'%04d%02d%02d%02d%02d%02d%06d' % ( + dt.year, dt.month, dt.day, dt.hour, + dt.minute, dt.second, dt.microsecond + ) + else: + return u'%04d%02d%02d%02d%02d%02d' % ( + dt.year, dt.month, dt.day, dt.hour, + dt.minute, dt.second + ) From 60e8925280d0b02cef3cd76cb52a52f2e0fb63e6 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Thu, 3 Dec 2009 10:21:03 -0500 Subject: [PATCH 82/98] Changed is not to is when testing for list, tuple. Silly style thing. --- tests/xapian_tests/tests/xapian_backend.py | 1 + tests/xapian_tests/tests/xapian_query.py | 4 ++++ xapian_backend.py | 16 ++++++++-------- 3 files changed, 13 insertions(+), 8 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_backend.py b/tests/xapian_tests/tests/xapian_backend.py index 86f9af0..ceb3200 100644 --- a/tests/xapian_tests/tests/xapian_backend.py +++ b/tests/xapian_tests/tests/xapian_backend.py @@ -130,6 +130,7 @@ class XapianSearchBackendTestCase(TestCase): {'flag': u'f', 'name': u'david2', 'text': u'indexed!\n2', 'sites': u"['2', '4', '6']", 'pub_date': u'20090223000000', 'value': u'000000000010', 'id': u'tests.xapianmockmodel.2', 'slug': u'http://example.com/2', 'popularity': '\xb4p', 'django_id': u'2', 'django_ct': u'tests.xapianmockmodel'}, {'flag': u't', 'name': u'david3', 'text': u'indexed!\n3', 'sites': u"['3', '6', '9']", 'pub_date': u'20090222000000', 'value': u'000000000015', 'id': u'tests.xapianmockmodel.3', 'slug': u'http://example.com/3', 'popularity': '\xcb\x98', 'django_id': u'3', 'django_ct': u'tests.xapianmockmodel'} ]) + import pdb; pdb.set_trace() def test_duplicate_update(self): self.sb.update(self.msi, self.sample_objs) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index 7ceed88..bcc02dc 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -47,6 +47,10 @@ class XapianSearchQueryTestCase(TestCase): self.sq.add_filter(SQ(content=True)) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(true)') + def test_build_query_date(self): + self.sq.add_filter(SQ(content=datetime.date(2009, 5, 8))) + self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(20090508000000)') + def test_build_query_datetime(self): self.sq.add_filter(SQ(content=datetime.datetime(2009, 5, 8, 11, 28))) self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(20090508112800)') diff --git a/xapian_backend.py b/xapian_backend.py index 3c7c5b3..63c9aa7 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -734,10 +734,10 @@ class SearchQuery(BaseSearchQuery): expression, term = child field, filter_type = search_node.split_expression(expression) - if not isinstance(term, (list, tuple)): - term = _marshal_term(term) - else: + if isinstance(term, (list, tuple)): term = [_marshal_term(t) for t in term] + else: + term = _marshal_term(term) if field == 'content': query_list.append(self._content_field(term, is_not)) @@ -928,11 +928,11 @@ def _marshal_term(term): term = _marshal_datetime(term) elif isinstance(term, datetime.date): term = _marshal_date(term) - elif isinstance(term, bool): - if term: - term = u'true' - else: - term = u'false' + # elif isinstance(term, bool): + # if term: + # term = u'true' + # else: + # term = u'false' else: term = force_unicode(term).lower() return term From a6e76709730b4241957dde2f4e07a183263959a9 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Thu, 3 Dec 2009 12:20:04 -0500 Subject: [PATCH 83/98] Added spelling suggestion --- tests/xapian_tests/tests/xapian_backend.py | 216 +++++++++++++++++++-- tests/xapian_tests/tests/xapian_query.py | 57 +++--- xapian_backend.py | 59 ++++-- 3 files changed, 276 insertions(+), 56 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_backend.py b/tests/xapian_tests/tests/xapian_backend.py index ceb3200..136ed99 100644 --- a/tests/xapian_tests/tests/xapian_backend.py +++ b/tests/xapian_tests/tests/xapian_backend.py @@ -1,4 +1,5 @@ # Copyright (C) 2009 David Sauve, Trapeze. All rights reserved. +# Based on original code by Daniel Lindsley as part of the Haystack test suite. import cPickle as pickle import datetime @@ -10,10 +11,12 @@ from django.conf import settings from django.db import models from django.test import TestCase -from haystack import indexes, sites -from haystack.backends.xapian_backend import SearchBackend, _marshal_value +from haystack import indexes, sites, backends +from haystack.backends.xapian_backend import SearchBackend, SearchQuery, _marshal_value +from haystack.exceptions import HaystackError +from haystack.query import SearchQuerySet, SQ -from core.models import MockTag, AnotherMockModel +from core.models import MockTag, MockModel, AnotherMockModel class XapianMockModel(models.Model): @@ -130,7 +133,6 @@ class XapianSearchBackendTestCase(TestCase): {'flag': u'f', 'name': u'david2', 'text': u'indexed!\n2', 'sites': u"['2', '4', '6']", 'pub_date': u'20090223000000', 'value': u'000000000010', 'id': u'tests.xapianmockmodel.2', 'slug': u'http://example.com/2', 'popularity': '\xb4p', 'django_id': u'2', 'django_ct': u'tests.xapianmockmodel'}, {'flag': u't', 'name': u'david3', 'text': u'indexed!\n3', 'sites': u"['3', '6', '9']", 'pub_date': u'20090222000000', 'value': u'000000000015', 'id': u'tests.xapianmockmodel.3', 'slug': u'http://example.com/3', 'popularity': '\xcb\x98', 'django_id': u'3', 'django_ct': u'tests.xapianmockmodel'} ]) - import pdb; pdb.set_trace() def test_duplicate_update(self): self.sb.update(self.msi, self.sample_objs) @@ -247,18 +249,18 @@ class XapianSearchBackendTestCase(TestCase): # self.assertEqual(self.sb.search('Index', highlight=True)['hits'], 3) # self.assertEqual([result.highlighted['text'] for result in self.sb.search('Index', highlight=True)['results']], ['Indexed!\n1', 'Indexed!\n2', 'Indexed!\n3']) - # def test_spelling_suggestion(self): - # self.sb.update(self.msi, self.sample_objs) - # self.assertEqual(len(self.xapian_search('')), 3) - # - # self.assertEqual(self.sb.search('indxe')['hits'], 0) - # self.assertEqual(self.sb.search('indxe')['spelling_suggestion'], 'indexed') - # - # self.assertEqual(self.sb.search('indxed')['hits'], 0) - # self.assertEqual(self.sb.search('indxed')['spelling_suggestion'], 'indexed') - # - # self.assertEqual(self.sb.search('indx')['hits'], 0) - # self.assertEqual(self.sb.search('indx', spelling_query='indexy')['spelling_suggestion'], 'indexed') + def test_spelling_suggestion(self): + self.sb.update(self.msi, self.sample_objs) + self.assertEqual(len(self.xapian_search('')), 3) + + self.assertEqual(self.sb.search(xapian.Query('indxe'))['hits'], 0) + self.assertEqual(self.sb.search(xapian.Query('indxe'))['spelling_suggestion'], 'indexed') + + self.assertEqual(self.sb.search(xapian.Query('indxed'))['hits'], 0) + self.assertEqual(self.sb.search(xapian.Query('indxed'))['spelling_suggestion'], 'indexed') + + self.assertEqual(self.sb.search(xapian.Query('indx'))['hits'], 0) + self.assertEqual(self.sb.search(xapian.Query('indx'), spelling_query='indexy')['spelling_suggestion'], 'indexed') # def test_more_like_this(self): # self.sb.update(self.msi, self.sample_objs) @@ -341,3 +343,185 @@ class XapianSearchBackendTestCase(TestCase): {'column': 5, 'field_name': 'flag', 'type': 'boolean', 'multi_valued': 'false'}, {'column': 6, 'field_name': 'pub_date', 'type': 'date', 'multi_valued': 'false'}, ]) + + +# class LiveXapianSearchQueryTestCase(TestCase): +# fixtures = ['initial_data.json'] +# +# def setUp(self): +# super(LiveXapianSearchQueryTestCase, self).setUp() +# +# self.sq = SearchQuery(backend=SearchBackend()) +# +# # Force indexing of the content. +# for mock in MockModel.objects.all(): +# mock.save() +# +# def test_get_spelling(self): +# self.sq.add_filter(SQ(content='Indexy')) +# self.assertEqual(self.sq.get_spelling_suggestion(), u'index') +# self.assertEqual(self.sq.get_spelling_suggestion('indexy'), u'index') +# +# def test_log_query(self): +# from django.conf import settings +# from haystack import backends +# backends.reset_search_queries() +# self.assertEqual(len(backends.queries), 0) +# +# # Stow. +# old_debug = settings.DEBUG +# settings.DEBUG = False +# +# len(self.sq.get_results()) +# self.assertEqual(len(backends.queries), 0) +# +# settings.DEBUG = True +# # Redefine it to clear out the cached results. +# self.sq = SearchQuery(backend=SearchBackend()) +# self.sq.add_filter(SQ(name='bar')) +# len(self.sq.get_results()) +# self.assertEqual(len(backends.queries), 1) +# self.assertEqual(backends.queries[0]['query_string'], 'xapian::Query(XNAMEbar)') +# +# # And again, for good measure. +# self.sq = SearchQuery(backend=SearchBackend()) +# self.sq.add_filter(SQ(name='bar')) +# self.sq.add_filter(SQ(text='moof')) +# len(self.sq.get_results()) +# self.assertEqual(len(backends.queries), 2) +# self.assertEqual(backends.queries[0]['query_string'].get_description(), u'xapian::Query(XNAMEbar)') +# self.assertEqual(backends.queries[1]['query_string'].get_description(), u'xapian::Query(XNAMEbar AND XTEXTmoof)') +# +# # Restore. +# settings.DEBUG = old_debug +# +# +# class LiveXapianSearchQuerySetTestCase(TestCase): +# """Used to test actual implementation details of the SearchQuerySet.""" +# fixtures = ['bulk_data.json'] +# +# def setUp(self): +# super(LiveXapianSearchQuerySetTestCase, self).setUp() +# +# # With the models registered, you get the proper bits. +# import haystack +# from haystack.sites import SearchSite +# +# # Stow. +# self.old_debug = settings.DEBUG +# settings.DEBUG = True +# self.old_site = haystack.site +# test_site = SearchSite() +# test_site.register(MockModel) +# haystack.site = test_site +# +# self.sqs = SearchQuerySet() +# +# # Force indexing of the content. +# for mock in MockModel.objects.all(): +# mock.save() +# +# def tearDown(self): +# # Restore. +# import haystack +# haystack.site = self.old_site +# settings.DEBUG = self.old_debug +# super(LiveXapianSearchQuerySetTestCase, self).tearDown() +# +# def test_load_all(self): +# sqs = self.sqs.load_all() +# self.assert_(isinstance(sqs, SearchQuerySet)) +# self.assert_(len(sqs) > 0) +# self.assertEqual(sqs[0].object.foo, u"Registering indexes in Haystack is very similar to registering models and ``ModelAdmin`` classes in the `Django admin site`_. If you want to override the default indexing behavior for your model you can specify your own ``SearchIndex`` class. This is useful for ensuring that future-dated or non-live content is not indexed and searchable. Our ``Note`` model has a ``pub_date`` field, so let's update our code to include our own ``SearchIndex`` to exclude indexing future-dated notes:") +# +# def test_load_all_queryset(self): +# sqs = self.sqs.load_all() +# self.assertRaises(HaystackError, sqs.load_all_queryset, MockModel, MockModel.objects.filter(id__gt=1)) +# +# def test_iter(self): +# backends.reset_search_queries() +# self.assertEqual(len(backends.queries), 0) +# sqs = self.sqs.all() +# results = [int(result.pk) for result in sqs] +# self.assertEqual(results, range(1, 24)) +# self.assertEqual(len(backends.queries), 3) +# +# def test_slice(self): +# backends.reset_search_queries() +# self.assertEqual(len(backends.queries), 0) +# results = self.sqs.all() +# self.assertEqual([int(result.pk) for result in results[1:11]], [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) +# self.assertEqual(len(backends.queries), 1) +# +# backends.reset_search_queries() +# self.assertEqual(len(backends.queries), 0) +# results = self.sqs.all() +# self.assertEqual(int(results[21].pk), 22) +# self.assertEqual(len(backends.queries), 1) +# +# def test_manual_iter(self): +# results = self.sqs.all() +# +# backends.reset_search_queries() +# self.assertEqual(len(backends.queries), 0) +# results = [int(result.pk) for result in results._manual_iter()] +# self.assertEqual(results, range(1, 24)) +# self.assertEqual(len(backends.queries), 3) +# +# def test_fill_cache(self): +# backends.reset_search_queries() +# self.assertEqual(len(backends.queries), 0) +# results = self.sqs.all() +# self.assertEqual(len(results._result_cache), 0) +# self.assertEqual(len(backends.queries), 0) +# results._fill_cache(0, 10) +# self.assertEqual(len([result for result in results._result_cache if result is not None]), 10) +# self.assertEqual(len(backends.queries), 1) +# results._fill_cache(10, 20) +# self.assertEqual(len([result for result in results._result_cache if result is not None]), 20) +# self.assertEqual(len(backends.queries), 2) +# +# def test_cache_is_full(self): +# backends.reset_search_queries() +# self.assertEqual(len(backends.queries), 0) +# self.assertEqual(self.sqs._cache_is_full(), False) +# results = self.sqs.all() +# fire_the_iterator_and_fill_cache = [result for result in results] +# self.assertEqual(results._cache_is_full(), True) +# self.assertEqual(len(backends.queries), 3) +# +# def test___and__(self): +# sqs1 = self.sqs.filter(content='foo') +# sqs2 = self.sqs.filter(content='bar') +# sqs = sqs1 & sqs2 +# +# self.assert_(isinstance(sqs, SearchQuerySet)) +# self.assertEqual(len(sqs.query.query_filter), 2) +# self.assertEqual(sqs.query.build_query().get_description(), u'Xapian::Query((foo AND bar))') +# +# # Now for something more complex... +# sqs3 = self.sqs.exclude(title='moof').filter(SQ(content='foo') | SQ(content='baz')) +# sqs4 = self.sqs.filter(content='bar') +# sqs = sqs3 & sqs4 +# +# self.assert_(isinstance(sqs, SearchQuerySet)) +# self.assertEqual(len(sqs.query.query_filter), 3) +# self.assertEqual(sqs.query.build_query().get_description(), u'Xapian::Query((( AND_NOT XTITLEmoof) AND (foo OR baz) AND bar))') +# +# def test___or__(self): +# sqs1 = self.sqs.filter(content='foo') +# sqs2 = self.sqs.filter(content='bar') +# sqs = sqs1 | sqs2 +# +# self.assert_(isinstance(sqs, SearchQuerySet)) +# self.assertEqual(len(sqs.query.query_filter), 2) +# self.assertEqual(sqs.query.build_query().get_description(), u'Xapian::Query((foo OR bar))') +# +# # Now for something more complex... +# sqs3 = self.sqs.exclude(title='moof').filter(SQ(content='foo') | SQ(content='baz')) +# sqs4 = self.sqs.filter(content='bar').models(MockModel) +# sqs = sqs3 | sqs4 +# +# self.assert_(isinstance(sqs, SearchQuerySet)) +# self.assertEqual(len(sqs.query.query_filter), 2) +# self.assertEqual(sqs.query.build_query().get_description(), u'Xapian::Query(((( AND_NOT XTITLEmoof) AND (foo OR baz)) OR bar))') diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index bcc02dc..02655f6 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -25,85 +25,85 @@ class XapianSearchQueryTestCase(TestCase): super(XapianSearchQueryTestCase, self).tearDown() def test_build_query_all(self): - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query()') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query()') def test_build_query_single_word(self): self.sq.add_filter(SQ(content='hello')) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(hello)') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(hello)') def test_build_query_single_word_not(self): self.sq.add_filter(~SQ(content='hello')) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(( AND_NOT hello))') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(( AND_NOT hello))') def test_build_query_single_word_field_exact(self): self.sq.add_filter(SQ(foo='hello')) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(XFOOhello)') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(XFOOhello)') def test_build_query_single_word_field_exact_not(self): self.sq.add_filter(~SQ(foo='hello')) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(( AND_NOT XFOOhello))') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(( AND_NOT XFOOhello))') def test_build_query_boolean(self): self.sq.add_filter(SQ(content=True)) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(true)') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(true)') def test_build_query_date(self): self.sq.add_filter(SQ(content=datetime.date(2009, 5, 8))) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(20090508000000)') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(20090508000000)') def test_build_query_datetime(self): self.sq.add_filter(SQ(content=datetime.datetime(2009, 5, 8, 11, 28))) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(20090508112800)') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(20090508112800)') def test_build_query_float(self): self.sq.add_filter(SQ(content=25.52)) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(25.52)') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(25.52)') def test_build_query_multiple_words_and(self): self.sq.add_filter(SQ(content='hello')) self.sq.add_filter(SQ(content='world')) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND world))') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((hello AND world))') def test_build_query_multiple_words_not(self): self.sq.add_filter(~SQ(content='hello')) self.sq.add_filter(~SQ(content='world')) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((( AND_NOT hello) AND ( AND_NOT world)))') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((( AND_NOT hello) AND ( AND_NOT world)))') def test_build_query_multiple_words_or(self): self.sq.add_filter(SQ(content='hello') | SQ(content='world')) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello OR world))') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((hello OR world))') def test_build_query_multiple_words_or_not(self): self.sq.add_filter(~SQ(content='hello') | ~SQ(content='world')) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((( AND_NOT hello) OR ( AND_NOT world)))') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((( AND_NOT hello) OR ( AND_NOT world)))') def test_build_query_multiple_words_mixed(self): self.sq.add_filter(SQ(content='why') | SQ(content='hello')) self.sq.add_filter(~SQ(content='world')) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(((why OR hello) AND ( AND_NOT world)))') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(((why OR hello) AND ( AND_NOT world)))') def test_build_query_multiple_word_field_exact(self): self.sq.add_filter(SQ(foo='hello')) self.sq.add_filter(SQ(bar='world')) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((XFOOhello AND XBARworld))') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((XFOOhello AND XBARworld))') def test_build_query_multiple_word_field_exact_not(self): self.sq.add_filter(~SQ(foo='hello')) self.sq.add_filter(~SQ(bar='world')) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((( AND_NOT XFOOhello) AND ( AND_NOT XBARworld)))') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((( AND_NOT XFOOhello) AND ( AND_NOT XBARworld)))') def test_build_query_phrase(self): self.sq.add_filter(SQ(content='hello world')) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello PHRASE 2 world))') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((hello PHRASE 2 world))') def test_build_query_phrase_not(self): self.sq.add_filter(~SQ(content='hello world')) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(( AND_NOT (hello PHRASE 2 world)))') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(( AND_NOT (hello PHRASE 2 world)))') def test_build_query_boost(self): self.sq.add_filter(SQ(content='hello')) self.sq.add_boost('world', 5) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello OR 5 * world))') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((hello OR 5 * world))') # def test_build_query_multiple_filter_types(self): # self.sq.add_filter(SQ(content='why')) @@ -112,37 +112,38 @@ class XapianSearchQueryTestCase(TestCase): # self.sq.add_filter(SQ(created__lt='2009-02-12 12:13:00')) # self.sq.add_filter(SQ(title__gte='B')) # self.sq.add_filter(SQ(id__in=[1, 2, 3])) - # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(why AND pub_date:[* TO "2009-02-10 01:59:00"] AND author:{david TO *} AND created:{* TO "2009-02-12 12:13:00"} AND title:[B TO *] AND (id:"1" OR id:"2" OR id:"3"))') + # self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(why AND pub_date:[* TO "2009-02-10 01:59:00"] AND author:{david TO *} AND created:{* TO "2009-02-12 12:13:00"} AND title:[B TO *] AND (id:"1" OR id:"2" OR id:"3"))') def test_build_query_in_filter_single_words(self): self.sq.add_filter(SQ(content='why')) self.sq.add_filter(SQ(title__in=["Dune", "Jaws"])) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((why AND (XTITLEdune OR XTITLEjaws)))') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((why AND (XTITLEdune OR XTITLEjaws)))') def test_build_query_not_in_filter_single_words(self): self.sq.add_filter(SQ(content='why')) self.sq.add_filter(~SQ(title__in=["Dune", "Jaws"])) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((why AND ( AND_NOT (XTITLEdune OR XTITLEjaws))))') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((why AND ( AND_NOT (XTITLEdune OR XTITLEjaws))))') def test_build_query_in_filter_multiple_words(self): self.sq.add_filter(SQ(content='why')) self.sq.add_filter(SQ(title__in=["A Famous Paper", "An Infamous Article"])) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((why AND ((XTITLEa PHRASE 3 XTITLEfamous PHRASE 3 XTITLEpaper) OR (XTITLEan PHRASE 3 XTITLEinfamous PHRASE 3 XTITLEarticle))))') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((why AND ((XTITLEa PHRASE 3 XTITLEfamous PHRASE 3 XTITLEpaper) OR (XTITLEan PHRASE 3 XTITLEinfamous PHRASE 3 XTITLEarticle))))') def test_build_query_not_in_filter_multiple_words(self): self.sq.add_filter(SQ(content='why')) self.sq.add_filter(~SQ(title__in=["A Famous Paper", "An Infamous Article"])) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((why AND ( AND_NOT ((XTITLEa PHRASE 3 XTITLEfamous PHRASE 3 XTITLEpaper) OR (XTITLEan PHRASE 3 XTITLEinfamous PHRASE 3 XTITLEarticle)))))') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((why AND ( AND_NOT ((XTITLEa PHRASE 3 XTITLEfamous PHRASE 3 XTITLEpaper) OR (XTITLEan PHRASE 3 XTITLEinfamous PHRASE 3 XTITLEarticle)))))') def test_build_query_in_filter_datetime(self): self.sq.add_filter(SQ(content='why')) self.sq.add_filter(SQ(pub_date__in=[datetime.datetime(2009, 7, 6, 1, 56, 21)])) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((why AND XPUB_DATE20090706015621))') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((why AND XPUB_DATE20090706015621))') # def test_build_query_wildcard_filter_types(self): # self.sq.add_filter(SQ(content='why')) # self.sq.add_filter(SQ(title__startswith='haystack')) - # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(why AND XTITLEhaystack*)') + # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((why AND XTITLEhaystack))') + # Because wildcards are expanded using existing documents, a more thorough test for this is performed in SearchBackend tests # def test_stem_single_word(self): # self.sq.add_filter(SQ(content='testing')) @@ -157,7 +158,7 @@ class XapianSearchQueryTestCase(TestCase): def test_build_query_with_models(self): self.sq.add_filter(SQ(content='hello')) self.sq.add_model(MockModel) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND 0 * XCONTENTTYPEcore.mockmodel))') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((hello AND 0 * XCONTENTTYPEcore.mockmodel))') self.sq.add_model(AnotherMockModel) - self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND (0 * XCONTENTTYPEcore.anothermockmodel OR 0 * XCONTENTTYPEcore.mockmodel)))') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((hello AND (0 * XCONTENTTYPEcore.anothermockmodel OR 0 * XCONTENTTYPEcore.mockmodel)))') diff --git a/xapian_backend.py b/xapian_backend.py index 63c9aa7..1b8480b 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -139,8 +139,8 @@ class SearchBackend(BaseSearchBackend): if field['field_name'] in data.keys(): prefix = DOCUMENT_CUSTOM_TERM_PREFIX + field['field_name'].upper() value = data[field['field_name']] - term_generator.index_text(force_unicode(value)) - term_generator.index_text(force_unicode(value), 1, prefix) + term_generator.index_text(_marshal_term(value)) + term_generator.index_text(_marshal_term(value), 1, prefix) document.add_value(field['column'], _marshal_value(value)) document.set_data(pickle.dumps( @@ -266,10 +266,10 @@ class SearchBackend(BaseSearchBackend): database = self._database() - # query, spelling_suggestion = self._query( - # database, query_string, narrow_queries, spelling_query - # ) - spelling_suggestion = '' + if getattr(settings, 'HAYSTACK_INCLUDE_SPELLING', False) is True: + spelling_suggestion = self._do_spelling_suggestion(database, query, spelling_query) + else: + spelling_suggestion = '' enquire = xapian.Enquire(database) enquire.set_query(query) @@ -609,6 +609,26 @@ class SearchBackend(BaseSearchBackend): return facet_dict + def _do_spelling_suggestion(self, database, query, spelling_query): + """ + Private method that returns a single spelling suggestion based on + `spelling_query` or `query`. + + Required arguments: + `database` -- The database to check spelling against + `query` -- The query to check + `spelling_query` -- If not None, this will be checked instead of `query` + + Returns a string with a suggested spelling + """ + if spelling_query: + if ' ' in spelling_query: + return ' '.join([database.get_spelling_suggestion(term) for term in spelling_query.split()]) + else: + return database.get_spelling_suggestion(spelling_query) + + return ' '.join([database.get_spelling_suggestion(term) for term in query]) + def _database(self, writable=False): """ Private method that returns a xapian.Database for use and sets up @@ -753,7 +773,7 @@ class SearchQuery(BaseSearchQuery): elif filter_type == 'lte': pass elif filter_type == 'startswith': - pass + query_list.append(self._filter_startswith(term, field, is_not)) elif filter_type == 'in': query_list.append(self._filter_in(term, field, is_not)) @@ -845,6 +865,26 @@ class SearchQuery(BaseSearchQuery): else: return xapian.Query(xapian.Query.OP_OR, query_list) + def _filter_startswith(self, term, field, is_not): + """ + Private method that returns a xapian.Query that searches for any term + that begins with `term` in a specified `field`. + + Required arguments: + ``term`` -- The terms to search for + ``field`` -- The field to search + ``is_not`` -- Invert the search results + + Returns: + A xapian.Query + """ + sb = SearchBackend() + for t in sb._database().allterms(): + print t + term_list = [term, 'foo'] + return self._filter_in(term_list, field, is_not) + + def _all_query(self): """ Private method that returns a xapian.Query that returns all documents, @@ -928,11 +968,6 @@ def _marshal_term(term): term = _marshal_datetime(term) elif isinstance(term, datetime.date): term = _marshal_date(term) - # elif isinstance(term, bool): - # if term: - # term = u'true' - # else: - # term = u'false' else: term = force_unicode(term).lower() return term From ccde83ff8cc9466543c61f7a5bf840288e4b9985 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Thu, 3 Dec 2009 13:49:26 -0500 Subject: [PATCH 84/98] Highlighting is working again --- tests/xapian_tests/tests/xapian_backend.py | 22 ++++++++++++-------- xapian_backend.py | 24 ++++++++++++++-------- 2 files changed, 28 insertions(+), 18 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_backend.py b/tests/xapian_tests/tests/xapian_backend.py index 136ed99..fb6893f 100644 --- a/tests/xapian_tests/tests/xapian_backend.py +++ b/tests/xapian_tests/tests/xapian_backend.py @@ -241,13 +241,13 @@ class XapianSearchBackendTestCase(TestCase): # results = self.sb.search('index', narrow_queries=set(['name:david1'])) # self.assertEqual(results['hits'], 1) - # def test_highlight(self): - # self.sb.update(self.msi, self.sample_objs) - # self.assertEqual(len(self.xapian_search('')), 3) - # - # self.assertEqual(self.sb.search('', highlight=True), {'hits': 0, 'results': []}) - # self.assertEqual(self.sb.search('Index', highlight=True)['hits'], 3) - # self.assertEqual([result.highlighted['text'] for result in self.sb.search('Index', highlight=True)['results']], ['Indexed!\n1', 'Indexed!\n2', 'Indexed!\n3']) + def test_highlight(self): + self.sb.update(self.msi, self.sample_objs) + self.assertEqual(len(self.xapian_search('')), 3) + + self.assertEqual(self.sb.search(xapian.Query(), highlight=True), {'hits': 0, 'results': []}) + self.assertEqual(self.sb.search(xapian.Query('indexed'), highlight=True)['hits'], 3) + self.assertEqual([result.highlighted['text'] for result in self.sb.search(xapian.Query('indexed'), highlight=True)['results']], ['indexed!\n1', 'indexed!\n2', 'indexed!\n3']) def test_spelling_suggestion(self): self.sb.update(self.msi, self.sample_objs) @@ -259,8 +259,12 @@ class XapianSearchBackendTestCase(TestCase): self.assertEqual(self.sb.search(xapian.Query('indxed'))['hits'], 0) self.assertEqual(self.sb.search(xapian.Query('indxed'))['spelling_suggestion'], 'indexed') - self.assertEqual(self.sb.search(xapian.Query('indx'))['hits'], 0) - self.assertEqual(self.sb.search(xapian.Query('indx'), spelling_query='indexy')['spelling_suggestion'], 'indexed') + self.assertEqual(self.sb.search(xapian.Query('foo'))['hits'], 0) + self.assertEqual(self.sb.search(xapian.Query('foo'), spelling_query='indexy')['spelling_suggestion'], 'indexed') + + self.assertEqual(self.sb.search(xapian.Query('XNAMEdavid'))['hits'], 0) + self.assertEqual(self.sb.search(xapian.Query('XNAMEdavid'))['spelling_suggestion'], 'david1') + # def test_more_like_this(self): # self.sb.update(self.msi, self.sample_objs) diff --git a/xapian_backend.py b/xapian_backend.py index 1b8480b..31963bf 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -301,10 +301,10 @@ class SearchBackend(BaseSearchBackend): for match in matches: app_label, module_name, pk, model_data = pickle.loads(match.document.get_data()) - if highlight and (len(query_string) > 0): + if highlight: model_data['highlighted'] = { self.content_field_name: self._do_highlight( - model_data.get(self.content_field_name), query_string + model_data.get(self.content_field_name), query ) } results.append( @@ -461,9 +461,9 @@ class SearchBackend(BaseSearchBackend): return (content_field_name, schema_fields) - def _do_highlight(self, content, text, tag='em'): + def _do_highlight(self, content, query, tag='em'): """ - Highlight `text` in `content` with html `tag`. + Highlight `query` terms in `content` with html `tag`. This method assumes that the input text (`content`) does not contain any special formatting. That is, it does not contain any html tags @@ -473,10 +473,11 @@ class SearchBackend(BaseSearchBackend): `content` -- Content to search for instances of `text` `text` -- The text to be highlighted """ - for term in [term.replace('*', '') for term in text.split()]: - if term not in self.RESERVED_WORDS: - term_re = re.compile(re.escape(term), re.IGNORECASE) - content = term_re.sub('<%s>%s' % (tag, term, tag), content) + for term in query: + for match in re.findall('[^A-Z]+', term): # Ignore field identifiers + match_re = re.compile(match, re.I) + content = match_re.sub('<%s>%s' % (tag, term, tag), content) + return content def _do_field_facets(self, results, field_facets): @@ -627,7 +628,12 @@ class SearchBackend(BaseSearchBackend): else: return database.get_spelling_suggestion(spelling_query) - return ' '.join([database.get_spelling_suggestion(term) for term in query]) + term_list = [] + for term in query: + for match in re.findall('[^A-Z]+', term): # Ignore field identifiers + term_list.append(database.get_spelling_suggestion(match)) + + return ' '.join(term_list) def _database(self, writable=False): """ From 585ccfdac768479c42d1710d21ec61b4115510f6 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Thu, 3 Dec 2009 16:40:33 -0500 Subject: [PATCH 85/98] More like this is working --- tests/xapian_tests/tests/xapian_backend.py | 23 +++++++++--------- xapian_backend.py | 28 ++++++++++------------ 2 files changed, 23 insertions(+), 28 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_backend.py b/tests/xapian_tests/tests/xapian_backend.py index fb6893f..8f6f939 100644 --- a/tests/xapian_tests/tests/xapian_backend.py +++ b/tests/xapian_tests/tests/xapian_backend.py @@ -264,19 +264,18 @@ class XapianSearchBackendTestCase(TestCase): self.assertEqual(self.sb.search(xapian.Query('XNAMEdavid'))['hits'], 0) self.assertEqual(self.sb.search(xapian.Query('XNAMEdavid'))['spelling_suggestion'], 'david1') - - # def test_more_like_this(self): - # self.sb.update(self.msi, self.sample_objs) - # self.assertEqual(len(self.xapian_search('')), 3) - # - # results = self.sb.more_like_this(self.sample_objs[0]) - # self.assertEqual(results['hits'], 2) - # self.assertEqual([result.pk for result in results['results']], [3, 2]) - # - # results = self.sb.more_like_this(self.sample_objs[0], additional_query_string='david3') - # self.assertEqual(results['hits'], 1) - # self.assertEqual([result.pk for result in results['results']], [3]) + def test_more_like_this(self): + self.sb.update(self.msi, self.sample_objs) + self.assertEqual(len(self.xapian_search('')), 3) + + results = self.sb.more_like_this(self.sample_objs[0]) + self.assertEqual(results['hits'], 2) + self.assertEqual([result.pk for result in results['results']], [3, 2]) + + results = self.sb.more_like_this(self.sample_objs[0], additional_query=xapian.Query('david3')) + self.assertEqual(results['hits'], 1) + self.assertEqual([result.pk for result in results['results']], [3]) # def test_order_by(self): # self.sb.update(self.msi, self.sample_objs) diff --git a/xapian_backend.py b/xapian_backend.py index 31963bf..c646428 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -325,7 +325,7 @@ class SearchBackend(BaseSearchBackend): 'spelling_suggestion': spelling_suggestion, } - def more_like_this(self, model_instance, additional_query_string=None, + def more_like_this(self, model_instance, additional_query=None, start_offset=0, end_offset=None, limit_to_registered_models=True, **kwargs): """ @@ -336,8 +336,7 @@ class SearchBackend(BaseSearchBackend): retrieving similar documents. Optional arguments: - `additional_query_string` -- An additional query string to narrow - results + `additional_query` -- An additional query to narrow results `start_offset` -- The starting offset (default=0) `end_offset` -- The ending offset (default=None), if None, then all documents `limit_to_registered_models` -- Limit returned results to models registered in the current `SearchSite` (default = True) @@ -379,19 +378,16 @@ class SearchBackend(BaseSearchBackend): query = xapian.Query( xapian.Query.OP_AND_NOT, [query, DOCUMENT_ID_TERM_PREFIX + get_identifier(model_instance)] ) - narrow_queries = None - if limit_to_registered_models: - registered_models = self.build_registered_models_list() - - if len(registered_models) > 0: - narrow_queries = set() - narrow_queries.add( - ' '.join(['django_ct:%s' % model for model in registered_models]) - ) - if additional_query_string: - additional_query, __unused__ = self._query( - database, additional_query_string, narrow_queries - ) + # narrow_queries = None + # if limit_to_registered_models: + # registered_models = self.build_registered_models_list() + # + # if len(registered_models) > 0: + # narrow_queries = set() + # narrow_queries.add( + # ' '.join(['django_ct:%s' % model for model in registered_models]) + # ) + if additional_query: query = xapian.Query( xapian.Query.OP_AND, query, additional_query ) From 012ba98ed100cde4b4000c745c6162df5fe52b09 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Thu, 3 Dec 2009 16:48:21 -0500 Subject: [PATCH 86/98] Added limit_to_registered_models in mlt --- tests/xapian_tests/tests/xapian_backend.py | 4 ++++ xapian_backend.py | 22 +++++++++++++--------- 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_backend.py b/tests/xapian_tests/tests/xapian_backend.py index 8f6f939..a2e46a9 100644 --- a/tests/xapian_tests/tests/xapian_backend.py +++ b/tests/xapian_tests/tests/xapian_backend.py @@ -277,6 +277,10 @@ class XapianSearchBackendTestCase(TestCase): self.assertEqual(results['hits'], 1) self.assertEqual([result.pk for result in results['results']], [3]) + results = self.sb.more_like_this(self.sample_objs[0], limit_to_registered_models=True) + self.assertEqual(results['hits'], 2) + self.assertEqual([result.pk for result in results['results']], [3, 2]) + # def test_order_by(self): # self.sb.update(self.msi, self.sample_objs) # diff --git a/xapian_backend.py b/xapian_backend.py index c646428..cf2a380 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -378,15 +378,19 @@ class SearchBackend(BaseSearchBackend): query = xapian.Query( xapian.Query.OP_AND_NOT, [query, DOCUMENT_ID_TERM_PREFIX + get_identifier(model_instance)] ) - # narrow_queries = None - # if limit_to_registered_models: - # registered_models = self.build_registered_models_list() - # - # if len(registered_models) > 0: - # narrow_queries = set() - # narrow_queries.add( - # ' '.join(['django_ct:%s' % model for model in registered_models]) - # ) + narrow_queries = [] + if limit_to_registered_models: + registered_models = self.build_registered_models_list() + + if len(registered_models) > 0: + query = xapian.Query( + xapian.Query.OP_AND, query, + xapian.Query( + xapian.Query.OP_OR, [ + xapian.Query('%s%s' % (DOCUMENT_CT_TERM_PREFIX, model)) for model in registered_models + ] + ) + ) if additional_query: query = xapian.Query( xapian.Query.OP_AND, query, additional_query From ae58bf85d29ea687879b99e114eb59f1c4bf6792 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Fri, 4 Dec 2009 09:13:10 -0500 Subject: [PATCH 87/98] field and date facets working --- tests/xapian_tests/tests/xapian_backend.py | 76 +++++++++++----------- 1 file changed, 38 insertions(+), 38 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_backend.py b/tests/xapian_tests/tests/xapian_backend.py index a2e46a9..28c4229 100644 --- a/tests/xapian_tests/tests/xapian_backend.py +++ b/tests/xapian_tests/tests/xapian_backend.py @@ -184,45 +184,45 @@ class XapianSearchBackendTestCase(TestCase): self.assertEqual(self.sb.search(xapian.Query(''))['hits'], 3) self.assertEqual([result.pk for result in self.sb.search(xapian.Query(''))['results']], [1, 2, 3]) - # def test_field_facets(self): - # self.sb.update(self.msi, self.sample_objs) - # self.assertEqual(len(self.xapian_search('')), 3) - # - # self.assertEqual(self.sb.search('', facets=['name']), {'hits': 0, 'results': []}) - # results = self.sb.search('index', facets=['name']) - # self.assertEqual(results['hits'], 3) - # self.assertEqual(results['facets']['fields']['name'], [('david1', 1), ('david2', 1), ('david3', 1)]) - # - # results = self.sb.search('index', facets=['flag']) - # self.assertEqual(results['hits'], 3) - # self.assertEqual(results['facets']['fields']['flag'], [(False, 1), (True, 2)]) - # - # results = self.sb.search('index', facets=['sites']) - # self.assertEqual(results['hits'], 3) - # self.assertEqual(results['facets']['fields']['sites'], [('1', 1), ('3', 2), ('2', 2), ('4', 1), ('6', 2), ('9', 1)]) + def test_field_facets(self): + self.sb.update(self.msi, self.sample_objs) + self.assertEqual(len(self.xapian_search('')), 3) + + self.assertEqual(self.sb.search(xapian.Query(), facets=['name']), {'hits': 0, 'results': []}) + results = self.sb.search(xapian.Query('indexed'), facets=['name']) + self.assertEqual(results['hits'], 3) + self.assertEqual(results['facets']['fields']['name'], [('david1', 1), ('david2', 1), ('david3', 1)]) + + results = self.sb.search(xapian.Query('indexed'), facets=['flag']) + self.assertEqual(results['hits'], 3) + self.assertEqual(results['facets']['fields']['flag'], [(False, 1), (True, 2)]) + + results = self.sb.search(xapian.Query('indexed'), facets=['sites']) + self.assertEqual(results['hits'], 3) + self.assertEqual(results['facets']['fields']['sites'], [('1', 1), ('3', 2), ('2', 2), ('4', 1), ('6', 2), ('9', 1)]) - # def test_date_facets(self): - # self.sb.update(self.msi, self.sample_objs) - # self.assertEqual(len(self.xapian_search('')), 3) - # - # self.assertEqual(self.sb.search('', date_facets={'pub_date': {'start_date': datetime.datetime(2008, 10, 26), 'end_date': datetime.datetime(2009, 3, 26), 'gap_by': 'month'}}), {'hits': 0, 'results': []}) - # results = self.sb.search('index', date_facets={'pub_date': {'start_date': datetime.datetime(2008, 10, 26), 'end_date': datetime.datetime(2009, 3, 26), 'gap_by': 'month'}}) - # self.assertEqual(results['hits'], 3) - # self.assertEqual(results['facets']['dates']['pub_date'], [ - # ('2009-02-26T00:00:00', 0), - # ('2009-01-26T00:00:00', 3), - # ('2008-12-26T00:00:00', 0), - # ('2008-11-26T00:00:00', 0), - # ('2008-10-26T00:00:00', 0), - # ]) - # - # results = self.sb.search('index', date_facets={'pub_date': {'start_date': datetime.datetime(2009, 02, 01), 'end_date': datetime.datetime(2009, 3, 15), 'gap_by': 'day', 'gap_amount': 15}}) - # self.assertEqual(results['hits'], 3) - # self.assertEqual(results['facets']['dates']['pub_date'], [ - # ('2009-03-03T00:00:00', 0), - # ('2009-02-16T00:00:00', 3), - # ('2009-02-01T00:00:00', 0) - # ]) + def test_date_facets(self): + self.sb.update(self.msi, self.sample_objs) + self.assertEqual(len(self.xapian_search('')), 3) + + self.assertEqual(self.sb.search(xapian.Query(), date_facets={'pub_date': {'start_date': datetime.datetime(2008, 10, 26), 'end_date': datetime.datetime(2009, 3, 26), 'gap_by': 'month'}}), {'hits': 0, 'results': []}) + results = self.sb.search(xapian.Query('indexed'), date_facets={'pub_date': {'start_date': datetime.datetime(2008, 10, 26), 'end_date': datetime.datetime(2009, 3, 26), 'gap_by': 'month'}}) + self.assertEqual(results['hits'], 3) + self.assertEqual(results['facets']['dates']['pub_date'], [ + ('2009-02-26T00:00:00', 0), + ('2009-01-26T00:00:00', 3), + ('2008-12-26T00:00:00', 0), + ('2008-11-26T00:00:00', 0), + ('2008-10-26T00:00:00', 0), + ]) + + results = self.sb.search(xapian.Query('indexed'), date_facets={'pub_date': {'start_date': datetime.datetime(2009, 02, 01), 'end_date': datetime.datetime(2009, 3, 15), 'gap_by': 'day', 'gap_amount': 15}}) + self.assertEqual(results['hits'], 3) + self.assertEqual(results['facets']['dates']['pub_date'], [ + ('2009-03-03T00:00:00', 0), + ('2009-02-16T00:00:00', 3), + ('2009-02-01T00:00:00', 0) + ]) # def test_query_facets(self): # self.sb.update(self.msi, self.sample_objs) From 617f623b6b11abfa4064411d65959c7ecacb3de0 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Fri, 4 Dec 2009 10:27:23 -0500 Subject: [PATCH 88/98] Order by is working --- tests/xapian_tests/tests/xapian_backend.py | 82 +++++++++++----------- xapian_backend.py | 30 ++++---- 2 files changed, 59 insertions(+), 53 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_backend.py b/tests/xapian_tests/tests/xapian_backend.py index 28c4229..3ed5a0b 100644 --- a/tests/xapian_tests/tests/xapian_backend.py +++ b/tests/xapian_tests/tests/xapian_backend.py @@ -228,18 +228,18 @@ class XapianSearchBackendTestCase(TestCase): # self.sb.update(self.msi, self.sample_objs) # self.assertEqual(len(self.xapian_search('')), 3) # - # self.assertEqual(self.sb.search('', query_facets={'name': 'da*'}), {'hits': 0, 'results': []}) - # results = self.sb.search('index', query_facets={'name': 'da*'}) + # self.assertEqual(self.sb.search(xapian.Query(), query_facets={'name': 'da*', {'hits': 0, 'results': []}) + # results = self.sb.search(xapian.Query('index'), query_facets={'name': 'da*'}) # self.assertEqual(results['hits'], 3) # self.assertEqual(results['facets']['queries']['name'], ('da*', 3)) - # def test_narrow_queries(self): - # self.sb.update(self.msi, self.sample_objs) - # self.assertEqual(len(self.xapian_search('')), 3) - # - # self.assertEqual(self.sb.search('', narrow_queries=set(['name:david1'])), {'hits': 0, 'results': []}) - # results = self.sb.search('index', narrow_queries=set(['name:david1'])) - # self.assertEqual(results['hits'], 1) + def test_narrow_queries(self): + self.sb.update(self.msi, self.sample_objs) + self.assertEqual(len(self.xapian_search('')), 3) + + self.assertEqual(self.sb.search(xapian.Query(), narrow_queries=set([xapian.Query('XNAMEdavid1')])), {'hits': 0, 'results': []}) + results = self.sb.search(xapian.Query('indexed'), narrow_queries=set([xapian.Query('XNAMEdavid1')])) + self.assertEqual(results['hits'], 1) def test_highlight(self): self.sb.update(self.msi, self.sample_objs) @@ -281,38 +281,38 @@ class XapianSearchBackendTestCase(TestCase): self.assertEqual(results['hits'], 2) self.assertEqual([result.pk for result in results['results']], [3, 2]) - # def test_order_by(self): - # self.sb.update(self.msi, self.sample_objs) - # - # results = self.sb.search('*', sort_by=['pub_date']) - # self.assertEqual([result.pk for result in results['results']], [3, 2, 1]) - # - # results = self.sb.search('*', sort_by=['-pub_date']) - # self.assertEqual([result.pk for result in results['results']], [1, 2, 3]) - # - # results = self.sb.search('*', sort_by=['id']) - # self.assertEqual([result.pk for result in results['results']], [1, 2, 3]) - # - # results = self.sb.search('*', sort_by=['-id']) - # self.assertEqual([result.pk for result in results['results']], [3, 2, 1]) - # - # results = self.sb.search('*', sort_by=['value']) - # self.assertEqual([result.pk for result in results['results']], [1, 2, 3]) - # - # results = self.sb.search('*', sort_by=['-value']) - # self.assertEqual([result.pk for result in results['results']], [3, 2, 1]) - # - # results = self.sb.search('*', sort_by=['popularity']) - # self.assertEqual([result.pk for result in results['results']], [2, 1, 3]) - # - # results = self.sb.search('*', sort_by=['-popularity']) - # self.assertEqual([result.pk for result in results['results']], [3, 1, 2]) - # - # results = self.sb.search('*', sort_by=['flag', 'id']) - # self.assertEqual([result.pk for result in results['results']], [2, 1, 3]) - # - # results = self.sb.search('*', sort_by=['flag', '-id']) - # self.assertEqual([result.pk for result in results['results']], [2, 3, 1]) + def test_order_by(self): + self.sb.update(self.msi, self.sample_objs) + + results = self.sb.search(xapian.Query(''), sort_by=['pub_date']) + self.assertEqual([result.pk for result in results['results']], [3, 2, 1]) + + results = self.sb.search(xapian.Query(''), sort_by=['-pub_date']) + self.assertEqual([result.pk for result in results['results']], [1, 2, 3]) + + results = self.sb.search(xapian.Query(''), sort_by=['id']) + self.assertEqual([result.pk for result in results['results']], [1, 2, 3]) + + results = self.sb.search(xapian.Query(''), sort_by=['-id']) + self.assertEqual([result.pk for result in results['results']], [3, 2, 1]) + + results = self.sb.search(xapian.Query(''), sort_by=['value']) + self.assertEqual([result.pk for result in results['results']], [1, 2, 3]) + + results = self.sb.search(xapian.Query(''), sort_by=['-value']) + self.assertEqual([result.pk for result in results['results']], [3, 2, 1]) + + results = self.sb.search(xapian.Query(''), sort_by=['popularity']) + self.assertEqual([result.pk for result in results['results']], [2, 1, 3]) + + results = self.sb.search(xapian.Query(''), sort_by=['-popularity']) + self.assertEqual([result.pk for result in results['results']], [3, 1, 2]) + + results = self.sb.search(xapian.Query(''), sort_by=['flag', 'id']) + self.assertEqual([result.pk for result in results['results']], [2, 1, 3]) + + results = self.sb.search(xapian.Query(''), sort_by=['flag', '-id']) + self.assertEqual([result.pk for result in results['results']], [2, 3, 1]) # def test_boost(self): # self.sb.update(self.msi, self.sample_objs) diff --git a/xapian_backend.py b/xapian_backend.py index cf2a380..f9e683e 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -253,17 +253,6 @@ class SearchBackend(BaseSearchBackend): 'hits': 0, } - # if limit_to_registered_models: - # if narrow_queries is None: - # narrow_queries = set() - # - # registered_models = self.build_registered_models_list() - # - # if len(registered_models) > 0: - # narrow_queries.add( - # ' '.join(['django_ct:%s' % model for model in registered_models]) - # ) - database = self._database() if getattr(settings, 'HAYSTACK_INCLUDE_SPELLING', False) is True: @@ -271,6 +260,24 @@ class SearchBackend(BaseSearchBackend): else: spelling_suggestion = '' + if narrow_queries is not None: + query = xapian.Query( + xapian.Query.OP_AND, query, xapian.Query(xapian.Query.OP_OR, list(narrow_queries)) + ) + + if limit_to_registered_models: + registered_models = self.build_registered_models_list() + + if len(registered_models) > 0: + query = xapian.Query( + xapian.Query.OP_AND, query, + xapian.Query( + xapian.Query.OP_OR, [ + xapian.Query('%s%s' % (DOCUMENT_CT_TERM_PREFIX, model)) for model in registered_models + ] + ) + ) + enquire = xapian.Enquire(database) enquire.set_query(query) @@ -378,7 +385,6 @@ class SearchBackend(BaseSearchBackend): query = xapian.Query( xapian.Query.OP_AND_NOT, [query, DOCUMENT_ID_TERM_PREFIX + get_identifier(model_instance)] ) - narrow_queries = [] if limit_to_registered_models: registered_models = self.build_registered_models_list() From 8ed2e9196e960846e08d4fa5bde923bfa81e80e3 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Fri, 4 Dec 2009 10:33:29 -0500 Subject: [PATCH 89/98] Removed commented code block --- tests/xapian_tests/tests/xapian_backend.py | 192 --------------------- 1 file changed, 192 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_backend.py b/tests/xapian_tests/tests/xapian_backend.py index 3ed5a0b..bd88bf5 100644 --- a/tests/xapian_tests/tests/xapian_backend.py +++ b/tests/xapian_tests/tests/xapian_backend.py @@ -314,16 +314,6 @@ class XapianSearchBackendTestCase(TestCase): results = self.sb.search(xapian.Query(''), sort_by=['flag', '-id']) self.assertEqual([result.pk for result in results['results']], [2, 3, 1]) - # def test_boost(self): - # self.sb.update(self.msi, self.sample_objs) - # - # # TODO: Need a better test case here. Possibly better test data? - # results = self.sb.search('*', boost={'true': 2}) - # self.assertEqual([result.pk for result in results['results']], [1, 3, 2]) - # - # results = self.sb.search('*', boost={'true': 1.5}) - # self.assertEqual([result.pk for result in results['results']], [1, 3, 2]) - def test__marshal_value(self): self.assertEqual(_marshal_value('abc'), u'abc') self.assertEqual(_marshal_value(1), '000000000001') @@ -350,185 +340,3 @@ class XapianSearchBackendTestCase(TestCase): {'column': 5, 'field_name': 'flag', 'type': 'boolean', 'multi_valued': 'false'}, {'column': 6, 'field_name': 'pub_date', 'type': 'date', 'multi_valued': 'false'}, ]) - - -# class LiveXapianSearchQueryTestCase(TestCase): -# fixtures = ['initial_data.json'] -# -# def setUp(self): -# super(LiveXapianSearchQueryTestCase, self).setUp() -# -# self.sq = SearchQuery(backend=SearchBackend()) -# -# # Force indexing of the content. -# for mock in MockModel.objects.all(): -# mock.save() -# -# def test_get_spelling(self): -# self.sq.add_filter(SQ(content='Indexy')) -# self.assertEqual(self.sq.get_spelling_suggestion(), u'index') -# self.assertEqual(self.sq.get_spelling_suggestion('indexy'), u'index') -# -# def test_log_query(self): -# from django.conf import settings -# from haystack import backends -# backends.reset_search_queries() -# self.assertEqual(len(backends.queries), 0) -# -# # Stow. -# old_debug = settings.DEBUG -# settings.DEBUG = False -# -# len(self.sq.get_results()) -# self.assertEqual(len(backends.queries), 0) -# -# settings.DEBUG = True -# # Redefine it to clear out the cached results. -# self.sq = SearchQuery(backend=SearchBackend()) -# self.sq.add_filter(SQ(name='bar')) -# len(self.sq.get_results()) -# self.assertEqual(len(backends.queries), 1) -# self.assertEqual(backends.queries[0]['query_string'], 'xapian::Query(XNAMEbar)') -# -# # And again, for good measure. -# self.sq = SearchQuery(backend=SearchBackend()) -# self.sq.add_filter(SQ(name='bar')) -# self.sq.add_filter(SQ(text='moof')) -# len(self.sq.get_results()) -# self.assertEqual(len(backends.queries), 2) -# self.assertEqual(backends.queries[0]['query_string'].get_description(), u'xapian::Query(XNAMEbar)') -# self.assertEqual(backends.queries[1]['query_string'].get_description(), u'xapian::Query(XNAMEbar AND XTEXTmoof)') -# -# # Restore. -# settings.DEBUG = old_debug -# -# -# class LiveXapianSearchQuerySetTestCase(TestCase): -# """Used to test actual implementation details of the SearchQuerySet.""" -# fixtures = ['bulk_data.json'] -# -# def setUp(self): -# super(LiveXapianSearchQuerySetTestCase, self).setUp() -# -# # With the models registered, you get the proper bits. -# import haystack -# from haystack.sites import SearchSite -# -# # Stow. -# self.old_debug = settings.DEBUG -# settings.DEBUG = True -# self.old_site = haystack.site -# test_site = SearchSite() -# test_site.register(MockModel) -# haystack.site = test_site -# -# self.sqs = SearchQuerySet() -# -# # Force indexing of the content. -# for mock in MockModel.objects.all(): -# mock.save() -# -# def tearDown(self): -# # Restore. -# import haystack -# haystack.site = self.old_site -# settings.DEBUG = self.old_debug -# super(LiveXapianSearchQuerySetTestCase, self).tearDown() -# -# def test_load_all(self): -# sqs = self.sqs.load_all() -# self.assert_(isinstance(sqs, SearchQuerySet)) -# self.assert_(len(sqs) > 0) -# self.assertEqual(sqs[0].object.foo, u"Registering indexes in Haystack is very similar to registering models and ``ModelAdmin`` classes in the `Django admin site`_. If you want to override the default indexing behavior for your model you can specify your own ``SearchIndex`` class. This is useful for ensuring that future-dated or non-live content is not indexed and searchable. Our ``Note`` model has a ``pub_date`` field, so let's update our code to include our own ``SearchIndex`` to exclude indexing future-dated notes:") -# -# def test_load_all_queryset(self): -# sqs = self.sqs.load_all() -# self.assertRaises(HaystackError, sqs.load_all_queryset, MockModel, MockModel.objects.filter(id__gt=1)) -# -# def test_iter(self): -# backends.reset_search_queries() -# self.assertEqual(len(backends.queries), 0) -# sqs = self.sqs.all() -# results = [int(result.pk) for result in sqs] -# self.assertEqual(results, range(1, 24)) -# self.assertEqual(len(backends.queries), 3) -# -# def test_slice(self): -# backends.reset_search_queries() -# self.assertEqual(len(backends.queries), 0) -# results = self.sqs.all() -# self.assertEqual([int(result.pk) for result in results[1:11]], [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) -# self.assertEqual(len(backends.queries), 1) -# -# backends.reset_search_queries() -# self.assertEqual(len(backends.queries), 0) -# results = self.sqs.all() -# self.assertEqual(int(results[21].pk), 22) -# self.assertEqual(len(backends.queries), 1) -# -# def test_manual_iter(self): -# results = self.sqs.all() -# -# backends.reset_search_queries() -# self.assertEqual(len(backends.queries), 0) -# results = [int(result.pk) for result in results._manual_iter()] -# self.assertEqual(results, range(1, 24)) -# self.assertEqual(len(backends.queries), 3) -# -# def test_fill_cache(self): -# backends.reset_search_queries() -# self.assertEqual(len(backends.queries), 0) -# results = self.sqs.all() -# self.assertEqual(len(results._result_cache), 0) -# self.assertEqual(len(backends.queries), 0) -# results._fill_cache(0, 10) -# self.assertEqual(len([result for result in results._result_cache if result is not None]), 10) -# self.assertEqual(len(backends.queries), 1) -# results._fill_cache(10, 20) -# self.assertEqual(len([result for result in results._result_cache if result is not None]), 20) -# self.assertEqual(len(backends.queries), 2) -# -# def test_cache_is_full(self): -# backends.reset_search_queries() -# self.assertEqual(len(backends.queries), 0) -# self.assertEqual(self.sqs._cache_is_full(), False) -# results = self.sqs.all() -# fire_the_iterator_and_fill_cache = [result for result in results] -# self.assertEqual(results._cache_is_full(), True) -# self.assertEqual(len(backends.queries), 3) -# -# def test___and__(self): -# sqs1 = self.sqs.filter(content='foo') -# sqs2 = self.sqs.filter(content='bar') -# sqs = sqs1 & sqs2 -# -# self.assert_(isinstance(sqs, SearchQuerySet)) -# self.assertEqual(len(sqs.query.query_filter), 2) -# self.assertEqual(sqs.query.build_query().get_description(), u'Xapian::Query((foo AND bar))') -# -# # Now for something more complex... -# sqs3 = self.sqs.exclude(title='moof').filter(SQ(content='foo') | SQ(content='baz')) -# sqs4 = self.sqs.filter(content='bar') -# sqs = sqs3 & sqs4 -# -# self.assert_(isinstance(sqs, SearchQuerySet)) -# self.assertEqual(len(sqs.query.query_filter), 3) -# self.assertEqual(sqs.query.build_query().get_description(), u'Xapian::Query((( AND_NOT XTITLEmoof) AND (foo OR baz) AND bar))') -# -# def test___or__(self): -# sqs1 = self.sqs.filter(content='foo') -# sqs2 = self.sqs.filter(content='bar') -# sqs = sqs1 | sqs2 -# -# self.assert_(isinstance(sqs, SearchQuerySet)) -# self.assertEqual(len(sqs.query.query_filter), 2) -# self.assertEqual(sqs.query.build_query().get_description(), u'Xapian::Query((foo OR bar))') -# -# # Now for something more complex... -# sqs3 = self.sqs.exclude(title='moof').filter(SQ(content='foo') | SQ(content='baz')) -# sqs4 = self.sqs.filter(content='bar').models(MockModel) -# sqs = sqs3 | sqs4 -# -# self.assert_(isinstance(sqs, SearchQuerySet)) -# self.assertEqual(len(sqs.query.query_filter), 2) -# self.assertEqual(sqs.query.build_query().get_description(), u'Xapian::Query(((( AND_NOT XTITLEmoof) AND (foo OR baz)) OR bar))') From da34c328492853f5b49cbc441ff62fed9113c6d6 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Fri, 4 Dec 2009 14:16:08 -0500 Subject: [PATCH 90/98] Added LiveLiveXapianSearchQueryTestCase --- tests/xapian_tests/tests/xapian_backend.py | 593 +++++++++++---------- tests/xapian_tests/tests/xapian_query.py | 6 - xapian_backend.py | 8 +- 3 files changed, 327 insertions(+), 280 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_backend.py b/tests/xapian_tests/tests/xapian_backend.py index bd88bf5..17e523e 100644 --- a/tests/xapian_tests/tests/xapian_backend.py +++ b/tests/xapian_tests/tests/xapian_backend.py @@ -15,6 +15,7 @@ from haystack import indexes, sites, backends from haystack.backends.xapian_backend import SearchBackend, SearchQuery, _marshal_value from haystack.exceptions import HaystackError from haystack.query import SearchQuerySet, SQ +from haystack.sites import SearchSite from core.models import MockTag, MockModel, AnotherMockModel @@ -58,285 +59,337 @@ class XapianMockSearchIndex(indexes.SearchIndex): return ['%d' % (i * obj.id) for i in xrange(1, 4)] -class XapianSearchSite(sites.SearchSite): - pass +# class XapianSearchBackendTestCase(TestCase): +# def setUp(self): +# super(XapianSearchBackendTestCase, self).setUp() +# +# self.site = SearchSite() +# self.sb = SearchBackend(site=self.site) +# self.msi = XapianMockSearchIndex(XapianMockModel, backend=self.sb) +# self.site.register(XapianMockModel, XapianMockSearchIndex) +# +# self.sample_objs = [] +# +# for i in xrange(1, 4): +# mock = XapianMockModel() +# mock.id = i +# mock.author = 'david%s' % i +# mock.pub_date = datetime.date(2009, 2, 25) - datetime.timedelta(days=i) +# mock.value = i * 5 +# mock.flag = bool(i % 2) +# mock.slug = 'http://example.com/%d' % i +# self.sample_objs.append(mock) +# +# self.sample_objs[0].popularity = 834.0 +# self.sample_objs[1].popularity = 35.5 +# self.sample_objs[2].popularity = 972.0 +# +# def tearDown(self): +# if os.path.exists(settings.HAYSTACK_XAPIAN_PATH): +# shutil.rmtree(settings.HAYSTACK_XAPIAN_PATH) +# +# super(XapianSearchBackendTestCase, self).tearDown() +# +# def xapian_search(self, query_string): +# database = xapian.Database(settings.HAYSTACK_XAPIAN_PATH) +# if query_string: +# qp = xapian.QueryParser() +# qp.set_database(database) +# query = qp.parse_query(query_string, xapian.QueryParser.FLAG_WILDCARD) +# else: +# query = xapian.Query(query_string) # Empty query matches all +# enquire = xapian.Enquire(database) +# enquire.set_query(query) +# matches = enquire.get_mset(0, database.get_doccount()) +# +# document_list = [] +# +# for match in matches: +# document = match.get_document() +# app_label, module_name, pk, model_data = pickle.loads(document.get_data()) +# for key, value in model_data.iteritems(): +# model_data[key] = _marshal_value(value) +# model_data['id'] = u'%s.%s.%d' % (app_label, module_name, pk) +# document_list.append(model_data) +# +# return document_list +# +# def silly_test(self): +# +# self.sb.update(self.msi, self.sample_objs) +# +# self.assertEqual(len(self.xapian_search('indexed')), 3) +# self.assertEqual(len(self.xapian_search('Indexed')), 3) +# +# def test_update(self): +# self.sb.update(self.msi, self.sample_objs) +# +# self.assertEqual(len(self.xapian_search('')), 3) +# self.assertEqual([dict(doc) for doc in self.xapian_search('')], [ +# {'flag': u't', 'name': u'david1', 'text': u'indexed!\n1', 'sites': u"['1', '2', '3']", 'pub_date': u'20090224000000', 'value': u'000000000005', 'id': u'tests.xapianmockmodel.1', 'slug': u'http://example.com/1', 'popularity': '\xca\x84', 'django_id': u'1', 'django_ct': u'tests.xapianmockmodel'}, +# {'flag': u'f', 'name': u'david2', 'text': u'indexed!\n2', 'sites': u"['2', '4', '6']", 'pub_date': u'20090223000000', 'value': u'000000000010', 'id': u'tests.xapianmockmodel.2', 'slug': u'http://example.com/2', 'popularity': '\xb4p', 'django_id': u'2', 'django_ct': u'tests.xapianmockmodel'}, +# {'flag': u't', 'name': u'david3', 'text': u'indexed!\n3', 'sites': u"['3', '6', '9']", 'pub_date': u'20090222000000', 'value': u'000000000015', 'id': u'tests.xapianmockmodel.3', 'slug': u'http://example.com/3', 'popularity': '\xcb\x98', 'django_id': u'3', 'django_ct': u'tests.xapianmockmodel'} +# ]) +# +# def test_duplicate_update(self): +# self.sb.update(self.msi, self.sample_objs) +# self.sb.update(self.msi, self.sample_objs) # Duplicates should be updated, not appended -- http://github.com/notanumber/xapian-haystack/issues/#issue/6 +# +# self.assertEqual(len(self.xapian_search('')), 3) +# +# def test_remove(self): +# self.sb.update(self.msi, self.sample_objs) +# self.assertEqual(len(self.xapian_search('')), 3) +# +# self.sb.remove(self.sample_objs[0]) +# self.assertEqual(len(self.xapian_search('')), 2) +# self.assertEqual([dict(doc) for doc in self.xapian_search('')], [ +# {'flag': u'f', 'name': u'david2', 'text': u'indexed!\n2', 'sites': u"['2', '4', '6']", 'pub_date': u'20090223000000', 'value': u'000000000010', 'id': u'tests.xapianmockmodel.2', 'slug': u'http://example.com/2', 'popularity': '\xb4p', 'django_id': u'2', 'django_ct': u'tests.xapianmockmodel'}, +# {'flag': u't', 'name': u'david3', 'text': u'indexed!\n3', 'sites': u"['3', '6', '9']", 'pub_date': u'20090222000000', 'value': u'000000000015', 'id': u'tests.xapianmockmodel.3', 'slug': u'http://example.com/3', 'popularity': '\xcb\x98', 'django_id': u'3', 'django_ct': u'tests.xapianmockmodel'} +# ]) +# +# def test_clear(self): +# self.sb.update(self.msi, self.sample_objs) +# self.assertEqual(len(self.xapian_search('')), 3) +# +# self.sb.clear() +# self.assertEqual(len(self.xapian_search('')), 0) +# +# self.sb.update(self.msi, self.sample_objs) +# self.assertEqual(len(self.xapian_search('')), 3) +# +# self.sb.clear([AnotherMockModel]) +# self.assertEqual(len(self.xapian_search('')), 3) +# +# self.sb.clear([XapianMockModel]) +# self.assertEqual(len(self.xapian_search('')), 0) +# +# self.sb.update(self.msi, self.sample_objs) +# self.assertEqual(len(self.xapian_search('')), 3) +# +# self.sb.clear([AnotherMockModel, XapianMockModel]) +# self.assertEqual(len(self.xapian_search('')), 0) +# +# def test_search(self): +# self.sb.update(self.msi, self.sample_objs) +# self.assertEqual(len(self.xapian_search('')), 3) +# +# self.assertEqual(self.sb.search(xapian.Query()), {'hits': 0, 'results': []}) +# self.assertEqual(self.sb.search(xapian.Query(''))['hits'], 3) +# self.assertEqual([result.pk for result in self.sb.search(xapian.Query(''))['results']], [1, 2, 3]) +# self.assertEqual(self.sb.search(xapian.Query('indexed'))['hits'], 3) +# self.assertEqual([result.pk for result in self.sb.search(xapian.Query(''))['results']], [1, 2, 3]) +# +# def test_field_facets(self): +# self.sb.update(self.msi, self.sample_objs) +# self.assertEqual(len(self.xapian_search('')), 3) +# +# self.assertEqual(self.sb.search(xapian.Query(), facets=['name']), {'hits': 0, 'results': []}) +# results = self.sb.search(xapian.Query('indexed'), facets=['name']) +# self.assertEqual(results['hits'], 3) +# self.assertEqual(results['facets']['fields']['name'], [('david1', 1), ('david2', 1), ('david3', 1)]) +# +# results = self.sb.search(xapian.Query('indexed'), facets=['flag']) +# self.assertEqual(results['hits'], 3) +# self.assertEqual(results['facets']['fields']['flag'], [(False, 1), (True, 2)]) +# +# results = self.sb.search(xapian.Query('indexed'), facets=['sites']) +# self.assertEqual(results['hits'], 3) +# self.assertEqual(results['facets']['fields']['sites'], [('1', 1), ('3', 2), ('2', 2), ('4', 1), ('6', 2), ('9', 1)]) +# +# def test_date_facets(self): +# self.sb.update(self.msi, self.sample_objs) +# self.assertEqual(len(self.xapian_search('')), 3) +# +# self.assertEqual(self.sb.search(xapian.Query(), date_facets={'pub_date': {'start_date': datetime.datetime(2008, 10, 26), 'end_date': datetime.datetime(2009, 3, 26), 'gap_by': 'month'}}), {'hits': 0, 'results': []}) +# results = self.sb.search(xapian.Query('indexed'), date_facets={'pub_date': {'start_date': datetime.datetime(2008, 10, 26), 'end_date': datetime.datetime(2009, 3, 26), 'gap_by': 'month'}}) +# self.assertEqual(results['hits'], 3) +# self.assertEqual(results['facets']['dates']['pub_date'], [ +# ('2009-02-26T00:00:00', 0), +# ('2009-01-26T00:00:00', 3), +# ('2008-12-26T00:00:00', 0), +# ('2008-11-26T00:00:00', 0), +# ('2008-10-26T00:00:00', 0), +# ]) +# +# results = self.sb.search(xapian.Query('indexed'), date_facets={'pub_date': {'start_date': datetime.datetime(2009, 02, 01), 'end_date': datetime.datetime(2009, 3, 15), 'gap_by': 'day', 'gap_amount': 15}}) +# self.assertEqual(results['hits'], 3) +# self.assertEqual(results['facets']['dates']['pub_date'], [ +# ('2009-03-03T00:00:00', 0), +# ('2009-02-16T00:00:00', 3), +# ('2009-02-01T00:00:00', 0) +# ]) +# +# # def test_query_facets(self): +# # self.sb.update(self.msi, self.sample_objs) +# # self.assertEqual(len(self.xapian_search('')), 3) +# # +# # self.assertEqual(self.sb.search(xapian.Query(), query_facets={'name': 'da*', {'hits': 0, 'results': []}) +# # results = self.sb.search(xapian.Query('index'), query_facets={'name': 'da*'}) +# # self.assertEqual(results['hits'], 3) +# # self.assertEqual(results['facets']['queries']['name'], ('da*', 3)) +# +# def test_narrow_queries(self): +# self.sb.update(self.msi, self.sample_objs) +# self.assertEqual(len(self.xapian_search('')), 3) +# +# self.assertEqual(self.sb.search(xapian.Query(), narrow_queries=set([xapian.Query('XNAMEdavid1')])), {'hits': 0, 'results': []}) +# results = self.sb.search(xapian.Query('indexed'), narrow_queries=set([xapian.Query('XNAMEdavid1')])) +# self.assertEqual(results['hits'], 1) +# +# def test_highlight(self): +# self.sb.update(self.msi, self.sample_objs) +# self.assertEqual(len(self.xapian_search('')), 3) +# +# self.assertEqual(self.sb.search(xapian.Query(), highlight=True), {'hits': 0, 'results': []}) +# self.assertEqual(self.sb.search(xapian.Query('indexed'), highlight=True)['hits'], 3) +# self.assertEqual([result.highlighted['text'] for result in self.sb.search(xapian.Query('indexed'), highlight=True)['results']], ['indexed!\n1', 'indexed!\n2', 'indexed!\n3']) +# +# def test_spelling_suggestion(self): +# self.sb.update(self.msi, self.sample_objs) +# self.assertEqual(len(self.xapian_search('')), 3) +# +# self.assertEqual(self.sb.search(xapian.Query('indxe'))['hits'], 0) +# self.assertEqual(self.sb.search(xapian.Query('indxe'))['spelling_suggestion'], 'indexed') +# +# self.assertEqual(self.sb.search(xapian.Query('indxed'))['hits'], 0) +# self.assertEqual(self.sb.search(xapian.Query('indxed'))['spelling_suggestion'], 'indexed') +# +# self.assertEqual(self.sb.search(xapian.Query('foo'))['hits'], 0) +# self.assertEqual(self.sb.search(xapian.Query('foo'), spelling_query='indexy')['spelling_suggestion'], 'indexed') +# +# self.assertEqual(self.sb.search(xapian.Query('XNAMEdavid'))['hits'], 0) +# self.assertEqual(self.sb.search(xapian.Query('XNAMEdavid'))['spelling_suggestion'], 'david1') +# +# def test_more_like_this(self): +# self.sb.update(self.msi, self.sample_objs) +# self.assertEqual(len(self.xapian_search('')), 3) +# +# results = self.sb.more_like_this(self.sample_objs[0]) +# self.assertEqual(results['hits'], 2) +# self.assertEqual([result.pk for result in results['results']], [3, 2]) +# +# results = self.sb.more_like_this(self.sample_objs[0], additional_query=xapian.Query('david3')) +# self.assertEqual(results['hits'], 1) +# self.assertEqual([result.pk for result in results['results']], [3]) +# +# results = self.sb.more_like_this(self.sample_objs[0], limit_to_registered_models=True) +# self.assertEqual(results['hits'], 2) +# self.assertEqual([result.pk for result in results['results']], [3, 2]) +# +# def test_order_by(self): +# self.sb.update(self.msi, self.sample_objs) +# +# results = self.sb.search(xapian.Query(''), sort_by=['pub_date']) +# self.assertEqual([result.pk for result in results['results']], [3, 2, 1]) +# +# results = self.sb.search(xapian.Query(''), sort_by=['-pub_date']) +# self.assertEqual([result.pk for result in results['results']], [1, 2, 3]) +# +# results = self.sb.search(xapian.Query(''), sort_by=['id']) +# self.assertEqual([result.pk for result in results['results']], [1, 2, 3]) +# +# results = self.sb.search(xapian.Query(''), sort_by=['-id']) +# self.assertEqual([result.pk for result in results['results']], [3, 2, 1]) +# +# results = self.sb.search(xapian.Query(''), sort_by=['value']) +# self.assertEqual([result.pk for result in results['results']], [1, 2, 3]) +# +# results = self.sb.search(xapian.Query(''), sort_by=['-value']) +# self.assertEqual([result.pk for result in results['results']], [3, 2, 1]) +# +# results = self.sb.search(xapian.Query(''), sort_by=['popularity']) +# self.assertEqual([result.pk for result in results['results']], [2, 1, 3]) +# +# results = self.sb.search(xapian.Query(''), sort_by=['-popularity']) +# self.assertEqual([result.pk for result in results['results']], [3, 1, 2]) +# +# results = self.sb.search(xapian.Query(''), sort_by=['flag', 'id']) +# self.assertEqual([result.pk for result in results['results']], [2, 1, 3]) +# +# results = self.sb.search(xapian.Query(''), sort_by=['flag', '-id']) +# self.assertEqual([result.pk for result in results['results']], [2, 3, 1]) +# +# def test__marshal_value(self): +# self.assertEqual(_marshal_value('abc'), u'abc') +# self.assertEqual(_marshal_value(1), '000000000001') +# self.assertEqual(_marshal_value(2653), '000000002653') +# self.assertEqual(_marshal_value(25.5), '\xb2`') +# self.assertEqual(_marshal_value([1, 2, 3]), u'[1, 2, 3]') +# self.assertEqual(_marshal_value((1, 2, 3)), u'(1, 2, 3)') +# self.assertEqual(_marshal_value({'a': 1, 'c': 3, 'b': 2}), u"{'a': 1, 'c': 3, 'b': 2}") +# self.assertEqual(_marshal_value(datetime.datetime(2009, 5, 9, 16, 14)), u'20090509161400') +# self.assertEqual(_marshal_value(datetime.datetime(2009, 5, 9, 0, 0)), u'20090509000000') +# self.assertEqual(_marshal_value(datetime.datetime(1899, 5, 18, 0, 0)), u'18990518000000') +# self.assertEqual(_marshal_value(datetime.datetime(2009, 5, 18, 1, 16, 30, 250)), u'20090518011630000250') +# +# def test_build_schema(self): +# (content_field_name, fields) = self.sb.build_schema(self.site.all_searchfields()) +# self.assertEqual(content_field_name, 'text') +# self.assertEqual(len(fields), 7) +# self.assertEqual(fields, [ +# {'column': 0, 'field_name': 'name', 'type': 'text', 'multi_valued': 'false'}, +# {'column': 1, 'field_name': 'text', 'type': 'text', 'multi_valued': 'false'}, +# {'column': 2, 'field_name': 'popularity', 'type': 'float', 'multi_valued': 'false'}, +# {'column': 3, 'field_name': 'sites', 'type': 'text', 'multi_valued': 'true'}, +# {'column': 4, 'field_name': 'value', 'type': 'long', 'multi_valued': 'false'}, +# {'column': 5, 'field_name': 'flag', 'type': 'boolean', 'multi_valued': 'false'}, +# {'column': 6, 'field_name': 'pub_date', 'type': 'date', 'multi_valued': 'false'}, +# ]) -class XapianSearchBackendTestCase(TestCase): +class LiveXapianMockSearchIndex(indexes.SearchIndex): + text = indexes.CharField(document=True, use_template=True) + name = indexes.CharField(model_attr='author') + pub_date = indexes.DateField(model_attr='pub_date') + + +class LiveXapianSearchQueryTestCase(TestCase): + fixtures = ['initial_data.json'] + def setUp(self): - super(XapianSearchBackendTestCase, self).setUp() - - self.site = XapianSearchSite() - self.sb = SearchBackend(site=self.site) - self.msi = XapianMockSearchIndex(XapianMockModel, backend=self.sb) - self.site.register(XapianMockModel, XapianMockSearchIndex) - - self.sample_objs = [] - - for i in xrange(1, 4): - mock = XapianMockModel() - mock.id = i - mock.author = 'david%s' % i - mock.pub_date = datetime.date(2009, 2, 25) - datetime.timedelta(days=i) - mock.value = i * 5 - mock.flag = bool(i % 2) - mock.slug = 'http://example.com/%d' % i - self.sample_objs.append(mock) - - self.sample_objs[0].popularity = 834.0 - self.sample_objs[1].popularity = 35.5 - self.sample_objs[2].popularity = 972.0 - - def tearDown(self): - if os.path.exists(settings.HAYSTACK_XAPIAN_PATH): - shutil.rmtree(settings.HAYSTACK_XAPIAN_PATH) + super(LiveXapianSearchQueryTestCase, self).setUp() - super(XapianSearchBackendTestCase, self).tearDown() - - def xapian_search(self, query_string): - database = xapian.Database(settings.HAYSTACK_XAPIAN_PATH) - if query_string: - qp = xapian.QueryParser() - qp.set_database(database) - query = qp.parse_query(query_string, xapian.QueryParser.FLAG_WILDCARD) - else: - query = xapian.Query(query_string) # Empty query matches all - enquire = xapian.Enquire(database) - enquire.set_query(query) - matches = enquire.get_mset(0, database.get_doccount()) - - document_list = [] - - for match in matches: - document = match.get_document() - app_label, module_name, pk, model_data = pickle.loads(document.get_data()) - for key, value in model_data.iteritems(): - model_data[key] = _marshal_value(value) - model_data['id'] = u'%s.%s.%d' % (app_label, module_name, pk) - document_list.append(model_data) + site = SearchSite() + backend = SearchBackend(site=site) + index = LiveXapianMockSearchIndex(MockModel, backend=backend) + site.register(MockModel, LiveXapianMockSearchIndex) + backend.update(index, MockModel.objects.all()) - return document_list - - def silly_test(self): - - self.sb.update(self.msi, self.sample_objs) - - self.assertEqual(len(self.xapian_search('indexed')), 3) - self.assertEqual(len(self.xapian_search('Indexed')), 3) - - def test_update(self): - self.sb.update(self.msi, self.sample_objs) - - self.assertEqual(len(self.xapian_search('')), 3) - self.assertEqual([dict(doc) for doc in self.xapian_search('')], [ - {'flag': u't', 'name': u'david1', 'text': u'indexed!\n1', 'sites': u"['1', '2', '3']", 'pub_date': u'20090224000000', 'value': u'000000000005', 'id': u'tests.xapianmockmodel.1', 'slug': u'http://example.com/1', 'popularity': '\xca\x84', 'django_id': u'1', 'django_ct': u'tests.xapianmockmodel'}, - {'flag': u'f', 'name': u'david2', 'text': u'indexed!\n2', 'sites': u"['2', '4', '6']", 'pub_date': u'20090223000000', 'value': u'000000000010', 'id': u'tests.xapianmockmodel.2', 'slug': u'http://example.com/2', 'popularity': '\xb4p', 'django_id': u'2', 'django_ct': u'tests.xapianmockmodel'}, - {'flag': u't', 'name': u'david3', 'text': u'indexed!\n3', 'sites': u"['3', '6', '9']", 'pub_date': u'20090222000000', 'value': u'000000000015', 'id': u'tests.xapianmockmodel.3', 'slug': u'http://example.com/3', 'popularity': '\xcb\x98', 'django_id': u'3', 'django_ct': u'tests.xapianmockmodel'} - ]) + self.sq = SearchQuery(backend=backend) - def test_duplicate_update(self): - self.sb.update(self.msi, self.sample_objs) - self.sb.update(self.msi, self.sample_objs) # Duplicates should be updated, not appended -- http://github.com/notanumber/xapian-haystack/issues/#issue/6 - - self.assertEqual(len(self.xapian_search('')), 3) + def test_get_spelling(self): + self.sq.add_filter(SQ(content='indxd')) + self.assertEqual(self.sq.get_spelling_suggestion(), u'indexed') + self.assertEqual(self.sq.get_spelling_suggestion('indxd'), u'indexed') - def test_remove(self): - self.sb.update(self.msi, self.sample_objs) - self.assertEqual(len(self.xapian_search('')), 3) - - self.sb.remove(self.sample_objs[0]) - self.assertEqual(len(self.xapian_search('')), 2) - self.assertEqual([dict(doc) for doc in self.xapian_search('')], [ - {'flag': u'f', 'name': u'david2', 'text': u'indexed!\n2', 'sites': u"['2', '4', '6']", 'pub_date': u'20090223000000', 'value': u'000000000010', 'id': u'tests.xapianmockmodel.2', 'slug': u'http://example.com/2', 'popularity': '\xb4p', 'django_id': u'2', 'django_ct': u'tests.xapianmockmodel'}, - {'flag': u't', 'name': u'david3', 'text': u'indexed!\n3', 'sites': u"['3', '6', '9']", 'pub_date': u'20090222000000', 'value': u'000000000015', 'id': u'tests.xapianmockmodel.3', 'slug': u'http://example.com/3', 'popularity': '\xcb\x98', 'django_id': u'3', 'django_ct': u'tests.xapianmockmodel'} - ]) + def test_log_query(self): + backends.reset_search_queries() + self.assertEqual(len(backends.queries), 0) - def test_clear(self): - self.sb.update(self.msi, self.sample_objs) - self.assertEqual(len(self.xapian_search('')), 3) - - self.sb.clear() - self.assertEqual(len(self.xapian_search('')), 0) - - self.sb.update(self.msi, self.sample_objs) - self.assertEqual(len(self.xapian_search('')), 3) - - self.sb.clear([AnotherMockModel]) - self.assertEqual(len(self.xapian_search('')), 3) - - self.sb.clear([XapianMockModel]) - self.assertEqual(len(self.xapian_search('')), 0) - - self.sb.update(self.msi, self.sample_objs) - self.assertEqual(len(self.xapian_search('')), 3) - - self.sb.clear([AnotherMockModel, XapianMockModel]) - self.assertEqual(len(self.xapian_search('')), 0) + # Stow. + old_debug = settings.DEBUG + settings.DEBUG = False - def test_search(self): - self.sb.update(self.msi, self.sample_objs) - self.assertEqual(len(self.xapian_search('')), 3) - - # Empty query - self.assertEqual(self.sb.search(xapian.Query()), {'hits': 0, 'results': []}) - - # Wildcard -- All - self.assertEqual(self.sb.search(xapian.Query(''))['hits'], 3) - self.assertEqual([result.pk for result in self.sb.search(xapian.Query(''))['results']], [1, 2, 3]) - - def test_field_facets(self): - self.sb.update(self.msi, self.sample_objs) - self.assertEqual(len(self.xapian_search('')), 3) - - self.assertEqual(self.sb.search(xapian.Query(), facets=['name']), {'hits': 0, 'results': []}) - results = self.sb.search(xapian.Query('indexed'), facets=['name']) - self.assertEqual(results['hits'], 3) - self.assertEqual(results['facets']['fields']['name'], [('david1', 1), ('david2', 1), ('david3', 1)]) + len(self.sq.get_results()) + self.assertEqual(len(backends.queries), 0) - results = self.sb.search(xapian.Query('indexed'), facets=['flag']) - self.assertEqual(results['hits'], 3) - self.assertEqual(results['facets']['fields']['flag'], [(False, 1), (True, 2)]) - - results = self.sb.search(xapian.Query('indexed'), facets=['sites']) - self.assertEqual(results['hits'], 3) - self.assertEqual(results['facets']['fields']['sites'], [('1', 1), ('3', 2), ('2', 2), ('4', 1), ('6', 2), ('9', 1)]) - - def test_date_facets(self): - self.sb.update(self.msi, self.sample_objs) - self.assertEqual(len(self.xapian_search('')), 3) + settings.DEBUG = True + # Redefine it to clear out the cached results. + self.sq = SearchQuery(backend=SearchBackend()) + self.sq.add_filter(SQ(name='bar')) + len(self.sq.get_results()) + self.assertEqual(len(backends.queries), 1) + self.assertEqual(backends.queries[0]['query_string'].get_description(), 'Xapian::Query(XNAMEbar)') - self.assertEqual(self.sb.search(xapian.Query(), date_facets={'pub_date': {'start_date': datetime.datetime(2008, 10, 26), 'end_date': datetime.datetime(2009, 3, 26), 'gap_by': 'month'}}), {'hits': 0, 'results': []}) - results = self.sb.search(xapian.Query('indexed'), date_facets={'pub_date': {'start_date': datetime.datetime(2008, 10, 26), 'end_date': datetime.datetime(2009, 3, 26), 'gap_by': 'month'}}) - self.assertEqual(results['hits'], 3) - self.assertEqual(results['facets']['dates']['pub_date'], [ - ('2009-02-26T00:00:00', 0), - ('2009-01-26T00:00:00', 3), - ('2008-12-26T00:00:00', 0), - ('2008-11-26T00:00:00', 0), - ('2008-10-26T00:00:00', 0), - ]) + # And again, for good measure. + self.sq = SearchQuery(backend=SearchBackend()) + self.sq.add_filter(SQ(name='bar')) + self.sq.add_filter(SQ(text='moof')) + len(self.sq.get_results()) + self.assertEqual(len(backends.queries), 2) + self.assertEqual(backends.queries[0]['query_string'].get_description(), u'Xapian::Query(XNAMEbar)') + self.assertEqual(backends.queries[1]['query_string'].get_description(), u'Xapian::Query((XNAMEbar AND XTEXTmoof))') - results = self.sb.search(xapian.Query('indexed'), date_facets={'pub_date': {'start_date': datetime.datetime(2009, 02, 01), 'end_date': datetime.datetime(2009, 3, 15), 'gap_by': 'day', 'gap_amount': 15}}) - self.assertEqual(results['hits'], 3) - self.assertEqual(results['facets']['dates']['pub_date'], [ - ('2009-03-03T00:00:00', 0), - ('2009-02-16T00:00:00', 3), - ('2009-02-01T00:00:00', 0) - ]) - - # def test_query_facets(self): - # self.sb.update(self.msi, self.sample_objs) - # self.assertEqual(len(self.xapian_search('')), 3) - # - # self.assertEqual(self.sb.search(xapian.Query(), query_facets={'name': 'da*', {'hits': 0, 'results': []}) - # results = self.sb.search(xapian.Query('index'), query_facets={'name': 'da*'}) - # self.assertEqual(results['hits'], 3) - # self.assertEqual(results['facets']['queries']['name'], ('da*', 3)) - - def test_narrow_queries(self): - self.sb.update(self.msi, self.sample_objs) - self.assertEqual(len(self.xapian_search('')), 3) - - self.assertEqual(self.sb.search(xapian.Query(), narrow_queries=set([xapian.Query('XNAMEdavid1')])), {'hits': 0, 'results': []}) - results = self.sb.search(xapian.Query('indexed'), narrow_queries=set([xapian.Query('XNAMEdavid1')])) - self.assertEqual(results['hits'], 1) - - def test_highlight(self): - self.sb.update(self.msi, self.sample_objs) - self.assertEqual(len(self.xapian_search('')), 3) - - self.assertEqual(self.sb.search(xapian.Query(), highlight=True), {'hits': 0, 'results': []}) - self.assertEqual(self.sb.search(xapian.Query('indexed'), highlight=True)['hits'], 3) - self.assertEqual([result.highlighted['text'] for result in self.sb.search(xapian.Query('indexed'), highlight=True)['results']], ['indexed!\n1', 'indexed!\n2', 'indexed!\n3']) - - def test_spelling_suggestion(self): - self.sb.update(self.msi, self.sample_objs) - self.assertEqual(len(self.xapian_search('')), 3) - - self.assertEqual(self.sb.search(xapian.Query('indxe'))['hits'], 0) - self.assertEqual(self.sb.search(xapian.Query('indxe'))['spelling_suggestion'], 'indexed') - - self.assertEqual(self.sb.search(xapian.Query('indxed'))['hits'], 0) - self.assertEqual(self.sb.search(xapian.Query('indxed'))['spelling_suggestion'], 'indexed') - - self.assertEqual(self.sb.search(xapian.Query('foo'))['hits'], 0) - self.assertEqual(self.sb.search(xapian.Query('foo'), spelling_query='indexy')['spelling_suggestion'], 'indexed') - - self.assertEqual(self.sb.search(xapian.Query('XNAMEdavid'))['hits'], 0) - self.assertEqual(self.sb.search(xapian.Query('XNAMEdavid'))['spelling_suggestion'], 'david1') - - def test_more_like_this(self): - self.sb.update(self.msi, self.sample_objs) - self.assertEqual(len(self.xapian_search('')), 3) - - results = self.sb.more_like_this(self.sample_objs[0]) - self.assertEqual(results['hits'], 2) - self.assertEqual([result.pk for result in results['results']], [3, 2]) - - results = self.sb.more_like_this(self.sample_objs[0], additional_query=xapian.Query('david3')) - self.assertEqual(results['hits'], 1) - self.assertEqual([result.pk for result in results['results']], [3]) - - results = self.sb.more_like_this(self.sample_objs[0], limit_to_registered_models=True) - self.assertEqual(results['hits'], 2) - self.assertEqual([result.pk for result in results['results']], [3, 2]) - - def test_order_by(self): - self.sb.update(self.msi, self.sample_objs) - - results = self.sb.search(xapian.Query(''), sort_by=['pub_date']) - self.assertEqual([result.pk for result in results['results']], [3, 2, 1]) - - results = self.sb.search(xapian.Query(''), sort_by=['-pub_date']) - self.assertEqual([result.pk for result in results['results']], [1, 2, 3]) - - results = self.sb.search(xapian.Query(''), sort_by=['id']) - self.assertEqual([result.pk for result in results['results']], [1, 2, 3]) - - results = self.sb.search(xapian.Query(''), sort_by=['-id']) - self.assertEqual([result.pk for result in results['results']], [3, 2, 1]) - - results = self.sb.search(xapian.Query(''), sort_by=['value']) - self.assertEqual([result.pk for result in results['results']], [1, 2, 3]) - - results = self.sb.search(xapian.Query(''), sort_by=['-value']) - self.assertEqual([result.pk for result in results['results']], [3, 2, 1]) - - results = self.sb.search(xapian.Query(''), sort_by=['popularity']) - self.assertEqual([result.pk for result in results['results']], [2, 1, 3]) - - results = self.sb.search(xapian.Query(''), sort_by=['-popularity']) - self.assertEqual([result.pk for result in results['results']], [3, 1, 2]) - - results = self.sb.search(xapian.Query(''), sort_by=['flag', 'id']) - self.assertEqual([result.pk for result in results['results']], [2, 1, 3]) - - results = self.sb.search(xapian.Query(''), sort_by=['flag', '-id']) - self.assertEqual([result.pk for result in results['results']], [2, 3, 1]) - - def test__marshal_value(self): - self.assertEqual(_marshal_value('abc'), u'abc') - self.assertEqual(_marshal_value(1), '000000000001') - self.assertEqual(_marshal_value(2653), '000000002653') - self.assertEqual(_marshal_value(25.5), '\xb2`') - self.assertEqual(_marshal_value([1, 2, 3]), u'[1, 2, 3]') - self.assertEqual(_marshal_value((1, 2, 3)), u'(1, 2, 3)') - self.assertEqual(_marshal_value({'a': 1, 'c': 3, 'b': 2}), u"{'a': 1, 'c': 3, 'b': 2}") - self.assertEqual(_marshal_value(datetime.datetime(2009, 5, 9, 16, 14)), u'20090509161400') - self.assertEqual(_marshal_value(datetime.datetime(2009, 5, 9, 0, 0)), u'20090509000000') - self.assertEqual(_marshal_value(datetime.datetime(1899, 5, 18, 0, 0)), u'18990518000000') - self.assertEqual(_marshal_value(datetime.datetime(2009, 5, 18, 1, 16, 30, 250)), u'20090518011630000250') - - def test_build_schema(self): - (content_field_name, fields) = self.sb.build_schema(self.site.all_searchfields()) - self.assertEqual(content_field_name, 'text') - self.assertEqual(len(fields), 7) - self.assertEqual(fields, [ - {'column': 0, 'field_name': 'name', 'type': 'text', 'multi_valued': 'false'}, - {'column': 1, 'field_name': 'text', 'type': 'text', 'multi_valued': 'false'}, - {'column': 2, 'field_name': 'popularity', 'type': 'float', 'multi_valued': 'false'}, - {'column': 3, 'field_name': 'sites', 'type': 'text', 'multi_valued': 'true'}, - {'column': 4, 'field_name': 'value', 'type': 'long', 'multi_valued': 'false'}, - {'column': 5, 'field_name': 'flag', 'type': 'boolean', 'multi_valued': 'false'}, - {'column': 6, 'field_name': 'pub_date', 'type': 'date', 'multi_valued': 'false'}, - ]) + # Restore. + settings.DEBUG = old_debug diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index 02655f6..2ef4f11 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -139,12 +139,6 @@ class XapianSearchQueryTestCase(TestCase): self.sq.add_filter(SQ(pub_date__in=[datetime.datetime(2009, 7, 6, 1, 56, 21)])) self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((why AND XPUB_DATE20090706015621))') - # def test_build_query_wildcard_filter_types(self): - # self.sq.add_filter(SQ(content='why')) - # self.sq.add_filter(SQ(title__startswith='haystack')) - # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((why AND XTITLEhaystack))') - # Because wildcards are expanded using existing documents, a more thorough test for this is performed in SearchBackend tests - # def test_stem_single_word(self): # self.sq.add_filter(SQ(content='testing')) # self.assertEqual(self.sq.build_query().get_description(), 'Xapian.Query(Ztest)') diff --git a/xapian_backend.py b/xapian_backend.py index f9e683e..83663be 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -134,7 +134,7 @@ class SearchBackend(BaseSearchBackend): document_id = DOCUMENT_ID_TERM_PREFIX + get_identifier(obj) data = index.prepare(obj) - + for field in self.schema: if field['field_name'] in data.keys(): prefix = DOCUMENT_CUSTOM_TERM_PREFIX + field['field_name'].upper() @@ -636,9 +636,9 @@ class SearchBackend(BaseSearchBackend): term_list = [] for term in query: - for match in re.findall('[^A-Z]+', term): # Ignore field identifiers + for match in re.findall('[^A-Z]+', term): # Ignore field identifiers term_list.append(database.get_spelling_suggestion(match)) - + return ' '.join(term_list) def _database(self, writable=False): @@ -653,7 +653,7 @@ class SearchBackend(BaseSearchBackend): """ if writable: self.content_field_name, self.schema = self.build_schema(self.site.all_searchfields()) - + database = xapian.WritableDatabase(settings.HAYSTACK_XAPIAN_PATH, xapian.DB_CREATE_OR_OPEN) database.set_metadata('schema', pickle.dumps(self.schema, pickle.HIGHEST_PROTOCOL)) database.set_metadata('content', pickle.dumps(self.content_field_name, pickle.HIGHEST_PROTOCOL)) From 4ea6f5eda1443ab481bf18b8cc128488c5fa0c3c Mon Sep 17 00:00:00 2001 From: David Sauve Date: Fri, 4 Dec 2009 14:42:06 -0500 Subject: [PATCH 91/98] Added parse_query utility method for SearchBackend. This takes a query_string and attempts to convert it to a xapian.Query for use by search --- tests/xapian_tests/tests/xapian_backend.py | 564 +++++++++++---------- xapian_backend.py | 78 +++ 2 files changed, 365 insertions(+), 277 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_backend.py b/tests/xapian_tests/tests/xapian_backend.py index 17e523e..a8a708b 100644 --- a/tests/xapian_tests/tests/xapian_backend.py +++ b/tests/xapian_tests/tests/xapian_backend.py @@ -59,283 +59,293 @@ class XapianMockSearchIndex(indexes.SearchIndex): return ['%d' % (i * obj.id) for i in xrange(1, 4)] -# class XapianSearchBackendTestCase(TestCase): -# def setUp(self): -# super(XapianSearchBackendTestCase, self).setUp() -# -# self.site = SearchSite() -# self.sb = SearchBackend(site=self.site) -# self.msi = XapianMockSearchIndex(XapianMockModel, backend=self.sb) -# self.site.register(XapianMockModel, XapianMockSearchIndex) -# -# self.sample_objs = [] -# -# for i in xrange(1, 4): -# mock = XapianMockModel() -# mock.id = i -# mock.author = 'david%s' % i -# mock.pub_date = datetime.date(2009, 2, 25) - datetime.timedelta(days=i) -# mock.value = i * 5 -# mock.flag = bool(i % 2) -# mock.slug = 'http://example.com/%d' % i -# self.sample_objs.append(mock) -# -# self.sample_objs[0].popularity = 834.0 -# self.sample_objs[1].popularity = 35.5 -# self.sample_objs[2].popularity = 972.0 -# -# def tearDown(self): -# if os.path.exists(settings.HAYSTACK_XAPIAN_PATH): -# shutil.rmtree(settings.HAYSTACK_XAPIAN_PATH) -# -# super(XapianSearchBackendTestCase, self).tearDown() -# -# def xapian_search(self, query_string): -# database = xapian.Database(settings.HAYSTACK_XAPIAN_PATH) -# if query_string: -# qp = xapian.QueryParser() -# qp.set_database(database) -# query = qp.parse_query(query_string, xapian.QueryParser.FLAG_WILDCARD) -# else: -# query = xapian.Query(query_string) # Empty query matches all -# enquire = xapian.Enquire(database) -# enquire.set_query(query) -# matches = enquire.get_mset(0, database.get_doccount()) -# -# document_list = [] -# -# for match in matches: -# document = match.get_document() -# app_label, module_name, pk, model_data = pickle.loads(document.get_data()) -# for key, value in model_data.iteritems(): -# model_data[key] = _marshal_value(value) -# model_data['id'] = u'%s.%s.%d' % (app_label, module_name, pk) -# document_list.append(model_data) -# -# return document_list -# -# def silly_test(self): -# -# self.sb.update(self.msi, self.sample_objs) -# -# self.assertEqual(len(self.xapian_search('indexed')), 3) -# self.assertEqual(len(self.xapian_search('Indexed')), 3) -# -# def test_update(self): -# self.sb.update(self.msi, self.sample_objs) -# -# self.assertEqual(len(self.xapian_search('')), 3) -# self.assertEqual([dict(doc) for doc in self.xapian_search('')], [ -# {'flag': u't', 'name': u'david1', 'text': u'indexed!\n1', 'sites': u"['1', '2', '3']", 'pub_date': u'20090224000000', 'value': u'000000000005', 'id': u'tests.xapianmockmodel.1', 'slug': u'http://example.com/1', 'popularity': '\xca\x84', 'django_id': u'1', 'django_ct': u'tests.xapianmockmodel'}, -# {'flag': u'f', 'name': u'david2', 'text': u'indexed!\n2', 'sites': u"['2', '4', '6']", 'pub_date': u'20090223000000', 'value': u'000000000010', 'id': u'tests.xapianmockmodel.2', 'slug': u'http://example.com/2', 'popularity': '\xb4p', 'django_id': u'2', 'django_ct': u'tests.xapianmockmodel'}, -# {'flag': u't', 'name': u'david3', 'text': u'indexed!\n3', 'sites': u"['3', '6', '9']", 'pub_date': u'20090222000000', 'value': u'000000000015', 'id': u'tests.xapianmockmodel.3', 'slug': u'http://example.com/3', 'popularity': '\xcb\x98', 'django_id': u'3', 'django_ct': u'tests.xapianmockmodel'} -# ]) -# -# def test_duplicate_update(self): -# self.sb.update(self.msi, self.sample_objs) -# self.sb.update(self.msi, self.sample_objs) # Duplicates should be updated, not appended -- http://github.com/notanumber/xapian-haystack/issues/#issue/6 -# -# self.assertEqual(len(self.xapian_search('')), 3) -# -# def test_remove(self): -# self.sb.update(self.msi, self.sample_objs) -# self.assertEqual(len(self.xapian_search('')), 3) -# -# self.sb.remove(self.sample_objs[0]) -# self.assertEqual(len(self.xapian_search('')), 2) -# self.assertEqual([dict(doc) for doc in self.xapian_search('')], [ -# {'flag': u'f', 'name': u'david2', 'text': u'indexed!\n2', 'sites': u"['2', '4', '6']", 'pub_date': u'20090223000000', 'value': u'000000000010', 'id': u'tests.xapianmockmodel.2', 'slug': u'http://example.com/2', 'popularity': '\xb4p', 'django_id': u'2', 'django_ct': u'tests.xapianmockmodel'}, -# {'flag': u't', 'name': u'david3', 'text': u'indexed!\n3', 'sites': u"['3', '6', '9']", 'pub_date': u'20090222000000', 'value': u'000000000015', 'id': u'tests.xapianmockmodel.3', 'slug': u'http://example.com/3', 'popularity': '\xcb\x98', 'django_id': u'3', 'django_ct': u'tests.xapianmockmodel'} -# ]) -# -# def test_clear(self): -# self.sb.update(self.msi, self.sample_objs) -# self.assertEqual(len(self.xapian_search('')), 3) -# -# self.sb.clear() -# self.assertEqual(len(self.xapian_search('')), 0) -# -# self.sb.update(self.msi, self.sample_objs) -# self.assertEqual(len(self.xapian_search('')), 3) -# -# self.sb.clear([AnotherMockModel]) -# self.assertEqual(len(self.xapian_search('')), 3) -# -# self.sb.clear([XapianMockModel]) -# self.assertEqual(len(self.xapian_search('')), 0) -# -# self.sb.update(self.msi, self.sample_objs) -# self.assertEqual(len(self.xapian_search('')), 3) -# -# self.sb.clear([AnotherMockModel, XapianMockModel]) -# self.assertEqual(len(self.xapian_search('')), 0) -# -# def test_search(self): -# self.sb.update(self.msi, self.sample_objs) -# self.assertEqual(len(self.xapian_search('')), 3) -# -# self.assertEqual(self.sb.search(xapian.Query()), {'hits': 0, 'results': []}) -# self.assertEqual(self.sb.search(xapian.Query(''))['hits'], 3) -# self.assertEqual([result.pk for result in self.sb.search(xapian.Query(''))['results']], [1, 2, 3]) -# self.assertEqual(self.sb.search(xapian.Query('indexed'))['hits'], 3) -# self.assertEqual([result.pk for result in self.sb.search(xapian.Query(''))['results']], [1, 2, 3]) -# -# def test_field_facets(self): -# self.sb.update(self.msi, self.sample_objs) -# self.assertEqual(len(self.xapian_search('')), 3) -# -# self.assertEqual(self.sb.search(xapian.Query(), facets=['name']), {'hits': 0, 'results': []}) -# results = self.sb.search(xapian.Query('indexed'), facets=['name']) -# self.assertEqual(results['hits'], 3) -# self.assertEqual(results['facets']['fields']['name'], [('david1', 1), ('david2', 1), ('david3', 1)]) -# -# results = self.sb.search(xapian.Query('indexed'), facets=['flag']) -# self.assertEqual(results['hits'], 3) -# self.assertEqual(results['facets']['fields']['flag'], [(False, 1), (True, 2)]) -# -# results = self.sb.search(xapian.Query('indexed'), facets=['sites']) -# self.assertEqual(results['hits'], 3) -# self.assertEqual(results['facets']['fields']['sites'], [('1', 1), ('3', 2), ('2', 2), ('4', 1), ('6', 2), ('9', 1)]) -# -# def test_date_facets(self): -# self.sb.update(self.msi, self.sample_objs) -# self.assertEqual(len(self.xapian_search('')), 3) -# -# self.assertEqual(self.sb.search(xapian.Query(), date_facets={'pub_date': {'start_date': datetime.datetime(2008, 10, 26), 'end_date': datetime.datetime(2009, 3, 26), 'gap_by': 'month'}}), {'hits': 0, 'results': []}) -# results = self.sb.search(xapian.Query('indexed'), date_facets={'pub_date': {'start_date': datetime.datetime(2008, 10, 26), 'end_date': datetime.datetime(2009, 3, 26), 'gap_by': 'month'}}) -# self.assertEqual(results['hits'], 3) -# self.assertEqual(results['facets']['dates']['pub_date'], [ -# ('2009-02-26T00:00:00', 0), -# ('2009-01-26T00:00:00', 3), -# ('2008-12-26T00:00:00', 0), -# ('2008-11-26T00:00:00', 0), -# ('2008-10-26T00:00:00', 0), -# ]) -# -# results = self.sb.search(xapian.Query('indexed'), date_facets={'pub_date': {'start_date': datetime.datetime(2009, 02, 01), 'end_date': datetime.datetime(2009, 3, 15), 'gap_by': 'day', 'gap_amount': 15}}) -# self.assertEqual(results['hits'], 3) -# self.assertEqual(results['facets']['dates']['pub_date'], [ -# ('2009-03-03T00:00:00', 0), -# ('2009-02-16T00:00:00', 3), -# ('2009-02-01T00:00:00', 0) -# ]) -# -# # def test_query_facets(self): -# # self.sb.update(self.msi, self.sample_objs) -# # self.assertEqual(len(self.xapian_search('')), 3) -# # -# # self.assertEqual(self.sb.search(xapian.Query(), query_facets={'name': 'da*', {'hits': 0, 'results': []}) -# # results = self.sb.search(xapian.Query('index'), query_facets={'name': 'da*'}) -# # self.assertEqual(results['hits'], 3) -# # self.assertEqual(results['facets']['queries']['name'], ('da*', 3)) -# -# def test_narrow_queries(self): -# self.sb.update(self.msi, self.sample_objs) -# self.assertEqual(len(self.xapian_search('')), 3) -# -# self.assertEqual(self.sb.search(xapian.Query(), narrow_queries=set([xapian.Query('XNAMEdavid1')])), {'hits': 0, 'results': []}) -# results = self.sb.search(xapian.Query('indexed'), narrow_queries=set([xapian.Query('XNAMEdavid1')])) -# self.assertEqual(results['hits'], 1) -# -# def test_highlight(self): -# self.sb.update(self.msi, self.sample_objs) -# self.assertEqual(len(self.xapian_search('')), 3) -# -# self.assertEqual(self.sb.search(xapian.Query(), highlight=True), {'hits': 0, 'results': []}) -# self.assertEqual(self.sb.search(xapian.Query('indexed'), highlight=True)['hits'], 3) -# self.assertEqual([result.highlighted['text'] for result in self.sb.search(xapian.Query('indexed'), highlight=True)['results']], ['indexed!\n1', 'indexed!\n2', 'indexed!\n3']) -# -# def test_spelling_suggestion(self): -# self.sb.update(self.msi, self.sample_objs) -# self.assertEqual(len(self.xapian_search('')), 3) -# -# self.assertEqual(self.sb.search(xapian.Query('indxe'))['hits'], 0) -# self.assertEqual(self.sb.search(xapian.Query('indxe'))['spelling_suggestion'], 'indexed') -# -# self.assertEqual(self.sb.search(xapian.Query('indxed'))['hits'], 0) -# self.assertEqual(self.sb.search(xapian.Query('indxed'))['spelling_suggestion'], 'indexed') -# -# self.assertEqual(self.sb.search(xapian.Query('foo'))['hits'], 0) -# self.assertEqual(self.sb.search(xapian.Query('foo'), spelling_query='indexy')['spelling_suggestion'], 'indexed') -# -# self.assertEqual(self.sb.search(xapian.Query('XNAMEdavid'))['hits'], 0) -# self.assertEqual(self.sb.search(xapian.Query('XNAMEdavid'))['spelling_suggestion'], 'david1') -# -# def test_more_like_this(self): -# self.sb.update(self.msi, self.sample_objs) -# self.assertEqual(len(self.xapian_search('')), 3) -# -# results = self.sb.more_like_this(self.sample_objs[0]) -# self.assertEqual(results['hits'], 2) -# self.assertEqual([result.pk for result in results['results']], [3, 2]) -# -# results = self.sb.more_like_this(self.sample_objs[0], additional_query=xapian.Query('david3')) -# self.assertEqual(results['hits'], 1) -# self.assertEqual([result.pk for result in results['results']], [3]) -# -# results = self.sb.more_like_this(self.sample_objs[0], limit_to_registered_models=True) -# self.assertEqual(results['hits'], 2) -# self.assertEqual([result.pk for result in results['results']], [3, 2]) -# -# def test_order_by(self): -# self.sb.update(self.msi, self.sample_objs) -# -# results = self.sb.search(xapian.Query(''), sort_by=['pub_date']) -# self.assertEqual([result.pk for result in results['results']], [3, 2, 1]) -# -# results = self.sb.search(xapian.Query(''), sort_by=['-pub_date']) -# self.assertEqual([result.pk for result in results['results']], [1, 2, 3]) -# -# results = self.sb.search(xapian.Query(''), sort_by=['id']) -# self.assertEqual([result.pk for result in results['results']], [1, 2, 3]) -# -# results = self.sb.search(xapian.Query(''), sort_by=['-id']) -# self.assertEqual([result.pk for result in results['results']], [3, 2, 1]) -# -# results = self.sb.search(xapian.Query(''), sort_by=['value']) -# self.assertEqual([result.pk for result in results['results']], [1, 2, 3]) -# -# results = self.sb.search(xapian.Query(''), sort_by=['-value']) -# self.assertEqual([result.pk for result in results['results']], [3, 2, 1]) -# -# results = self.sb.search(xapian.Query(''), sort_by=['popularity']) -# self.assertEqual([result.pk for result in results['results']], [2, 1, 3]) -# -# results = self.sb.search(xapian.Query(''), sort_by=['-popularity']) -# self.assertEqual([result.pk for result in results['results']], [3, 1, 2]) -# -# results = self.sb.search(xapian.Query(''), sort_by=['flag', 'id']) -# self.assertEqual([result.pk for result in results['results']], [2, 1, 3]) -# -# results = self.sb.search(xapian.Query(''), sort_by=['flag', '-id']) -# self.assertEqual([result.pk for result in results['results']], [2, 3, 1]) -# -# def test__marshal_value(self): -# self.assertEqual(_marshal_value('abc'), u'abc') -# self.assertEqual(_marshal_value(1), '000000000001') -# self.assertEqual(_marshal_value(2653), '000000002653') -# self.assertEqual(_marshal_value(25.5), '\xb2`') -# self.assertEqual(_marshal_value([1, 2, 3]), u'[1, 2, 3]') -# self.assertEqual(_marshal_value((1, 2, 3)), u'(1, 2, 3)') -# self.assertEqual(_marshal_value({'a': 1, 'c': 3, 'b': 2}), u"{'a': 1, 'c': 3, 'b': 2}") -# self.assertEqual(_marshal_value(datetime.datetime(2009, 5, 9, 16, 14)), u'20090509161400') -# self.assertEqual(_marshal_value(datetime.datetime(2009, 5, 9, 0, 0)), u'20090509000000') -# self.assertEqual(_marshal_value(datetime.datetime(1899, 5, 18, 0, 0)), u'18990518000000') -# self.assertEqual(_marshal_value(datetime.datetime(2009, 5, 18, 1, 16, 30, 250)), u'20090518011630000250') -# -# def test_build_schema(self): -# (content_field_name, fields) = self.sb.build_schema(self.site.all_searchfields()) -# self.assertEqual(content_field_name, 'text') -# self.assertEqual(len(fields), 7) -# self.assertEqual(fields, [ -# {'column': 0, 'field_name': 'name', 'type': 'text', 'multi_valued': 'false'}, -# {'column': 1, 'field_name': 'text', 'type': 'text', 'multi_valued': 'false'}, -# {'column': 2, 'field_name': 'popularity', 'type': 'float', 'multi_valued': 'false'}, -# {'column': 3, 'field_name': 'sites', 'type': 'text', 'multi_valued': 'true'}, -# {'column': 4, 'field_name': 'value', 'type': 'long', 'multi_valued': 'false'}, -# {'column': 5, 'field_name': 'flag', 'type': 'boolean', 'multi_valued': 'false'}, -# {'column': 6, 'field_name': 'pub_date', 'type': 'date', 'multi_valued': 'false'}, -# ]) +class XapianSearchBackendTestCase(TestCase): + def setUp(self): + super(XapianSearchBackendTestCase, self).setUp() + + self.site = SearchSite() + self.backend = SearchBackend(site=self.site) + self.index = XapianMockSearchIndex(XapianMockModel, backend=self.backend) + self.site.register(XapianMockModel, XapianMockSearchIndex) + + self.sample_objs = [] + + for i in xrange(1, 4): + mock = XapianMockModel() + mock.id = i + mock.author = 'david%s' % i + mock.pub_date = datetime.date(2009, 2, 25) - datetime.timedelta(days=i) + mock.value = i * 5 + mock.flag = bool(i % 2) + mock.slug = 'http://example.com/%d' % i + self.sample_objs.append(mock) + + self.sample_objs[0].popularity = 834.0 + self.sample_objs[1].popularity = 35.5 + self.sample_objs[2].popularity = 972.0 + + def tearDown(self): + if os.path.exists(settings.HAYSTACK_XAPIAN_PATH): + shutil.rmtree(settings.HAYSTACK_XAPIAN_PATH) + + super(XapianSearchBackendTestCase, self).tearDown() + + def xapian_search(self, query_string): + database = xapian.Database(settings.HAYSTACK_XAPIAN_PATH) + if query_string: + qp = xapian.QueryParser() + qp.set_database(database) + query = qp.parse_query(query_string, xapian.QueryParser.FLAG_WILDCARD) + else: + query = xapian.Query(query_string) # Empty query matches all + enquire = xapian.Enquire(database) + enquire.set_query(query) + matches = enquire.get_mset(0, database.get_doccount()) + + document_list = [] + + for match in matches: + document = match.get_document() + app_label, module_name, pk, model_data = pickle.loads(document.get_data()) + for key, value in model_data.iteritems(): + model_data[key] = _marshal_value(value) + model_data['id'] = u'%s.%s.%d' % (app_label, module_name, pk) + document_list.append(model_data) + + return document_list + + def silly_test(self): + + self.backend.update(self.index, self.sample_objs) + + self.assertEqual(len(self.xapian_search('indexed')), 3) + self.assertEqual(len(self.xapian_search('Indexed')), 3) + + def test_update(self): + self.backend.update(self.index, self.sample_objs) + + self.assertEqual(len(self.xapian_search('')), 3) + self.assertEqual([dict(doc) for doc in self.xapian_search('')], [ + {'flag': u't', 'name': u'david1', 'text': u'indexed!\n1', 'sites': u"['1', '2', '3']", 'pub_date': u'20090224000000', 'value': u'000000000005', 'id': u'tests.xapianmockmodel.1', 'slug': u'http://example.com/1', 'popularity': '\xca\x84', 'django_id': u'1', 'django_ct': u'tests.xapianmockmodel'}, + {'flag': u'f', 'name': u'david2', 'text': u'indexed!\n2', 'sites': u"['2', '4', '6']", 'pub_date': u'20090223000000', 'value': u'000000000010', 'id': u'tests.xapianmockmodel.2', 'slug': u'http://example.com/2', 'popularity': '\xb4p', 'django_id': u'2', 'django_ct': u'tests.xapianmockmodel'}, + {'flag': u't', 'name': u'david3', 'text': u'indexed!\n3', 'sites': u"['3', '6', '9']", 'pub_date': u'20090222000000', 'value': u'000000000015', 'id': u'tests.xapianmockmodel.3', 'slug': u'http://example.com/3', 'popularity': '\xcb\x98', 'django_id': u'3', 'django_ct': u'tests.xapianmockmodel'} + ]) + + def test_duplicate_update(self): + self.backend.update(self.index, self.sample_objs) + self.backend.update(self.index, self.sample_objs) # Duplicates should be updated, not appended -- http://github.com/notanumber/xapian-haystack/issues/#issue/6 + + self.assertEqual(len(self.xapian_search('')), 3) + + def test_remove(self): + self.backend.update(self.index, self.sample_objs) + self.assertEqual(len(self.xapian_search('')), 3) + + self.backend.remove(self.sample_objs[0]) + self.assertEqual(len(self.xapian_search('')), 2) + self.assertEqual([dict(doc) for doc in self.xapian_search('')], [ + {'flag': u'f', 'name': u'david2', 'text': u'indexed!\n2', 'sites': u"['2', '4', '6']", 'pub_date': u'20090223000000', 'value': u'000000000010', 'id': u'tests.xapianmockmodel.2', 'slug': u'http://example.com/2', 'popularity': '\xb4p', 'django_id': u'2', 'django_ct': u'tests.xapianmockmodel'}, + {'flag': u't', 'name': u'david3', 'text': u'indexed!\n3', 'sites': u"['3', '6', '9']", 'pub_date': u'20090222000000', 'value': u'000000000015', 'id': u'tests.xapianmockmodel.3', 'slug': u'http://example.com/3', 'popularity': '\xcb\x98', 'django_id': u'3', 'django_ct': u'tests.xapianmockmodel'} + ]) + + def test_clear(self): + self.backend.update(self.index, self.sample_objs) + self.assertEqual(len(self.xapian_search('')), 3) + + self.backend.clear() + self.assertEqual(len(self.xapian_search('')), 0) + + self.backend.update(self.index, self.sample_objs) + self.assertEqual(len(self.xapian_search('')), 3) + + self.backend.clear([AnotherMockModel]) + self.assertEqual(len(self.xapian_search('')), 3) + + self.backend.clear([XapianMockModel]) + self.assertEqual(len(self.xapian_search('')), 0) + + self.backend.update(self.index, self.sample_objs) + self.assertEqual(len(self.xapian_search('')), 3) + + self.backend.clear([AnotherMockModel, XapianMockModel]) + self.assertEqual(len(self.xapian_search('')), 0) + + def test_search(self): + self.backend.update(self.index, self.sample_objs) + self.assertEqual(len(self.xapian_search('')), 3) + + self.assertEqual(self.backend.search(xapian.Query()), {'hits': 0, 'results': []}) + self.assertEqual(self.backend.search(xapian.Query(''))['hits'], 3) + self.assertEqual([result.pk for result in self.backend.search(xapian.Query(''))['results']], [1, 2, 3]) + self.assertEqual(self.backend.search(xapian.Query('indexed'))['hits'], 3) + self.assertEqual([result.pk for result in self.backend.search(xapian.Query(''))['results']], [1, 2, 3]) + + def test_field_facets(self): + self.backend.update(self.index, self.sample_objs) + self.assertEqual(len(self.xapian_search('')), 3) + + self.assertEqual(self.backend.search(xapian.Query(), facets=['name']), {'hits': 0, 'results': []}) + results = self.backend.search(xapian.Query('indexed'), facets=['name']) + self.assertEqual(results['hits'], 3) + self.assertEqual(results['facets']['fields']['name'], [('david1', 1), ('david2', 1), ('david3', 1)]) + + results = self.backend.search(xapian.Query('indexed'), facets=['flag']) + self.assertEqual(results['hits'], 3) + self.assertEqual(results['facets']['fields']['flag'], [(False, 1), (True, 2)]) + + results = self.backend.search(xapian.Query('indexed'), facets=['sites']) + self.assertEqual(results['hits'], 3) + self.assertEqual(results['facets']['fields']['sites'], [('1', 1), ('3', 2), ('2', 2), ('4', 1), ('6', 2), ('9', 1)]) + + def test_date_facets(self): + self.backend.update(self.index, self.sample_objs) + self.assertEqual(len(self.xapian_search('')), 3) + + self.assertEqual(self.backend.search(xapian.Query(), date_facets={'pub_date': {'start_date': datetime.datetime(2008, 10, 26), 'end_date': datetime.datetime(2009, 3, 26), 'gap_by': 'month'}}), {'hits': 0, 'results': []}) + results = self.backend.search(xapian.Query('indexed'), date_facets={'pub_date': {'start_date': datetime.datetime(2008, 10, 26), 'end_date': datetime.datetime(2009, 3, 26), 'gap_by': 'month'}}) + self.assertEqual(results['hits'], 3) + self.assertEqual(results['facets']['dates']['pub_date'], [ + ('2009-02-26T00:00:00', 0), + ('2009-01-26T00:00:00', 3), + ('2008-12-26T00:00:00', 0), + ('2008-11-26T00:00:00', 0), + ('2008-10-26T00:00:00', 0), + ]) + + results = self.backend.search(xapian.Query('indexed'), date_facets={'pub_date': {'start_date': datetime.datetime(2009, 02, 01), 'end_date': datetime.datetime(2009, 3, 15), 'gap_by': 'day', 'gap_amount': 15}}) + self.assertEqual(results['hits'], 3) + self.assertEqual(results['facets']['dates']['pub_date'], [ + ('2009-03-03T00:00:00', 0), + ('2009-02-16T00:00:00', 3), + ('2009-02-01T00:00:00', 0) + ]) + + # def test_query_facets(self): + # self.backend.update(self.index, self.sample_objs) + # self.assertEqual(len(self.xapian_search('')), 3) + # + # self.assertEqual(self.backend.search(xapian.Query(), query_facets={'name': 'da*', {'hits': 0, 'results': []}) + # results = self.backend.search(xapian.Query('index'), query_facets={'name': 'da*'}) + # self.assertEqual(results['hits'], 3) + # self.assertEqual(results['facets']['queries']['name'], ('da*', 3)) + + def test_narrow_queries(self): + self.backend.update(self.index, self.sample_objs) + self.assertEqual(len(self.xapian_search('')), 3) + + self.assertEqual(self.backend.search(xapian.Query(), narrow_queries=set([xapian.Query('XNAMEdavid1')])), {'hits': 0, 'results': []}) + results = self.backend.search(xapian.Query('indexed'), narrow_queries=set([xapian.Query('XNAMEdavid1')])) + self.assertEqual(results['hits'], 1) + + def test_highlight(self): + self.backend.update(self.index, self.sample_objs) + self.assertEqual(len(self.xapian_search('')), 3) + + self.assertEqual(self.backend.search(xapian.Query(), highlight=True), {'hits': 0, 'results': []}) + self.assertEqual(self.backend.search(xapian.Query('indexed'), highlight=True)['hits'], 3) + self.assertEqual([result.highlighted['text'] for result in self.backend.search(xapian.Query('indexed'), highlight=True)['results']], ['indexed!\n1', 'indexed!\n2', 'indexed!\n3']) + + def test_spelling_suggestion(self): + self.backend.update(self.index, self.sample_objs) + self.assertEqual(len(self.xapian_search('')), 3) + + self.assertEqual(self.backend.search(xapian.Query('indxe'))['hits'], 0) + self.assertEqual(self.backend.search(xapian.Query('indxe'))['spelling_suggestion'], 'indexed') + + self.assertEqual(self.backend.search(xapian.Query('indxed'))['hits'], 0) + self.assertEqual(self.backend.search(xapian.Query('indxed'))['spelling_suggestion'], 'indexed') + + self.assertEqual(self.backend.search(xapian.Query('foo'))['hits'], 0) + self.assertEqual(self.backend.search(xapian.Query('foo'), spelling_query='indexy')['spelling_suggestion'], 'indexed') + + self.assertEqual(self.backend.search(xapian.Query('XNAMEdavid'))['hits'], 0) + self.assertEqual(self.backend.search(xapian.Query('XNAMEdavid'))['spelling_suggestion'], 'david1') + + def test_more_like_this(self): + self.backend.update(self.index, self.sample_objs) + self.assertEqual(len(self.xapian_search('')), 3) + + results = self.backend.more_like_this(self.sample_objs[0]) + self.assertEqual(results['hits'], 2) + self.assertEqual([result.pk for result in results['results']], [3, 2]) + + results = self.backend.more_like_this(self.sample_objs[0], additional_query=xapian.Query('david3')) + self.assertEqual(results['hits'], 1) + self.assertEqual([result.pk for result in results['results']], [3]) + + results = self.backend.more_like_this(self.sample_objs[0], limit_to_registered_models=True) + self.assertEqual(results['hits'], 2) + self.assertEqual([result.pk for result in results['results']], [3, 2]) + + def test_order_by(self): + self.backend.update(self.index, self.sample_objs) + + results = self.backend.search(xapian.Query(''), sort_by=['pub_date']) + self.assertEqual([result.pk for result in results['results']], [3, 2, 1]) + + results = self.backend.search(xapian.Query(''), sort_by=['-pub_date']) + self.assertEqual([result.pk for result in results['results']], [1, 2, 3]) + + results = self.backend.search(xapian.Query(''), sort_by=['id']) + self.assertEqual([result.pk for result in results['results']], [1, 2, 3]) + + results = self.backend.search(xapian.Query(''), sort_by=['-id']) + self.assertEqual([result.pk for result in results['results']], [3, 2, 1]) + + results = self.backend.search(xapian.Query(''), sort_by=['value']) + self.assertEqual([result.pk for result in results['results']], [1, 2, 3]) + + results = self.backend.search(xapian.Query(''), sort_by=['-value']) + self.assertEqual([result.pk for result in results['results']], [3, 2, 1]) + + results = self.backend.search(xapian.Query(''), sort_by=['popularity']) + self.assertEqual([result.pk for result in results['results']], [2, 1, 3]) + + results = self.backend.search(xapian.Query(''), sort_by=['-popularity']) + self.assertEqual([result.pk for result in results['results']], [3, 1, 2]) + + results = self.backend.search(xapian.Query(''), sort_by=['flag', 'id']) + self.assertEqual([result.pk for result in results['results']], [2, 1, 3]) + + results = self.backend.search(xapian.Query(''), sort_by=['flag', '-id']) + self.assertEqual([result.pk for result in results['results']], [2, 3, 1]) + + def test__marshal_value(self): + self.assertEqual(_marshal_value('abc'), u'abc') + self.assertEqual(_marshal_value(1), '000000000001') + self.assertEqual(_marshal_value(2653), '000000002653') + self.assertEqual(_marshal_value(25.5), '\xb2`') + self.assertEqual(_marshal_value([1, 2, 3]), u'[1, 2, 3]') + self.assertEqual(_marshal_value((1, 2, 3)), u'(1, 2, 3)') + self.assertEqual(_marshal_value({'a': 1, 'c': 3, 'b': 2}), u"{'a': 1, 'c': 3, 'b': 2}") + self.assertEqual(_marshal_value(datetime.datetime(2009, 5, 9, 16, 14)), u'20090509161400') + self.assertEqual(_marshal_value(datetime.datetime(2009, 5, 9, 0, 0)), u'20090509000000') + self.assertEqual(_marshal_value(datetime.datetime(1899, 5, 18, 0, 0)), u'18990518000000') + self.assertEqual(_marshal_value(datetime.datetime(2009, 5, 18, 1, 16, 30, 250)), u'20090518011630000250') + + def test_build_schema(self): + (content_field_name, fields) = self.backend.build_schema(self.site.all_searchfields()) + self.assertEqual(content_field_name, 'text') + self.assertEqual(len(fields), 7) + self.assertEqual(fields, [ + {'column': 0, 'field_name': 'name', 'type': 'text', 'multi_valued': 'false'}, + {'column': 1, 'field_name': 'text', 'type': 'text', 'multi_valued': 'false'}, + {'column': 2, 'field_name': 'popularity', 'type': 'float', 'multi_valued': 'false'}, + {'column': 3, 'field_name': 'sites', 'type': 'text', 'multi_valued': 'true'}, + {'column': 4, 'field_name': 'value', 'type': 'long', 'multi_valued': 'false'}, + {'column': 5, 'field_name': 'flag', 'type': 'boolean', 'multi_valued': 'false'}, + {'column': 6, 'field_name': 'pub_date', 'type': 'date', 'multi_valued': 'false'}, + ]) + + def test_parse_query(self): + self.backend.update(self.index, self.sample_objs) + self.assertEqual(self.backend.parse_query('indexed').get_description(), 'Xapian::Query((indexed:(pos=1) OR Zindex:(pos=1)))') + self.assertEqual(self.backend.parse_query('name:david').get_description(), 'Xapian::Query((XNAMEdavid1:(pos=1) OR XNAMEdavid2:(pos=1) OR XNAMEdavid3:(pos=1) OR ZXNAMEdavid:(pos=1)))') + self.assertEqual(self.backend.parse_query('name:david1..david2').get_description(), 'Xapian::Query(VALUE_RANGE 0 david1 david2)') + self.assertEqual(self.backend.parse_query('value:0..10').get_description(), 'Xapian::Query(VALUE_RANGE 4 000000000000 000000000010)') + self.assertEqual(self.backend.parse_query('value:..10').get_description(), 'Xapian::Query(VALUE_RANGE 4 -02147483648 000000000010)') + self.assertEqual(self.backend.parse_query('value:10..*').get_description(), 'Xapian::Query(VALUE_RANGE 4 000000000010 002147483647)') + self.assertEqual(self.backend.parse_query('popularity:25.5..100.0').get_description(), 'Xapian::Query(VALUE_RANGE 2 \xb2` \xba@)') class LiveXapianMockSearchIndex(indexes.SearchIndex): diff --git a/xapian_backend.py b/xapian_backend.py index 83663be..f6d36bc 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -33,6 +33,52 @@ DOCUMENT_CUSTOM_TERM_PREFIX = 'X' DOCUMENT_CT_TERM_PREFIX = DOCUMENT_CUSTOM_TERM_PREFIX + 'CONTENTTYPE' +class XHValueRangeProcessor(xapian.ValueRangeProcessor): + def __init__(self, sb): + self.sb = sb + xapian.ValueRangeProcessor.__init__(self) + + def __call__(self, begin, end): + """ + Construct a tuple for value range processing. + `begin` -- a string in the format ':[low_range]' + If 'low_range' is omitted, assume the smallest possible value. + `end` -- a string in the the format '[high_range|*]'. If '*', assume + the highest possible value. + Return a tuple of three strings: (column, low, high) + """ + colon = begin.find(':') + field_name = begin[:colon] + begin = begin[colon + 1:len(begin)] + for field_dict in self.sb.schema: + if field_dict['field_name'] == field_name: + if not begin: + if field_dict['type'] == 'text': + begin = u'a' # TODO: A better way of getting a min text value? + elif field_dict['type'] == 'long': + begin = -sys.maxint - 1 + elif field_dict['type'] == 'float': + begin = float('-inf') + elif field_dict['type'] == 'date' or field_dict['type'] == 'datetime': + begin = u'00010101000000' + elif end == '*': + if field_dict['type'] == 'text': + end = u'z' * 100 # TODO: A better way of getting a max text value? + elif field_dict['type'] == 'long': + end = sys.maxint + elif field_dict['type'] == 'float': + end = float('inf') + elif field_dict['type'] == 'date' or field_dict['type'] == 'datetime': + end = u'99990101000000' + if field_dict['type'] == 'float': + begin = _marshal_value(float(begin)) + end = _marshal_value(float(end)) + elif field_dict['type'] == 'long': + begin = _marshal_value(long(begin)) + end = _marshal_value(long(end)) + return field_dict['column'], str(begin), str(end) + + class XHExpandDecider(xapian.ExpandDecider): def __call__(self, term): """ @@ -425,6 +471,38 @@ class SearchBackend(BaseSearchBackend): 'spelling_suggestion': None, } + def parse_query(self, query_string): + """ + Given a `query_string`, will attempt to return a xapian.Query + + Required arguments: + ``query_string`` -- A query string to parse + + Returns a xapian.Query + """ + flags = xapian.QueryParser.FLAG_PARTIAL \ + | xapian.QueryParser.FLAG_PHRASE \ + | xapian.QueryParser.FLAG_BOOLEAN \ + | xapian.QueryParser.FLAG_LOVEHATE \ + | xapian.QueryParser.FLAG_WILDCARD \ + | xapian.QueryParser.FLAG_PURE_NOT + qp = xapian.QueryParser() + qp.set_database(self._database()) + qp.set_stemmer(xapian.Stem(self.language)) + qp.set_stemming_strategy(xapian.QueryParser.STEM_SOME) + qp.add_boolean_prefix('django_ct', DOCUMENT_CT_TERM_PREFIX) + + for field_dict in self.schema: + qp.add_prefix( + field_dict['field_name'], + DOCUMENT_CUSTOM_TERM_PREFIX + field_dict['field_name'].upper() + ) + + vrp = XHValueRangeProcessor(self) + qp.add_valuerangeprocessor(vrp) + + return qp.parse_query(query_string, flags) + def build_schema(self, fields): """ Build the schema from fields. From 253382b41a6ea1f85e81313584da82316b8654dc Mon Sep 17 00:00:00 2001 From: David Sauve Date: Fri, 4 Dec 2009 15:41:32 -0500 Subject: [PATCH 92/98] __startswith has been implemented in new branch --- tests/xapian_tests/tests/xapian_backend.py | 8 ++++++++ xapian_backend.py | 13 ++++++++++--- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_backend.py b/tests/xapian_tests/tests/xapian_backend.py index a8a708b..bcf63ca 100644 --- a/tests/xapian_tests/tests/xapian_backend.py +++ b/tests/xapian_tests/tests/xapian_backend.py @@ -373,6 +373,14 @@ class LiveXapianSearchQueryTestCase(TestCase): self.assertEqual(self.sq.get_spelling_suggestion(), u'indexed') self.assertEqual(self.sq.get_spelling_suggestion('indxd'), u'indexed') + def test_startswith(self): + self.sq.add_filter(SQ(name__startswith='da*')) + self.assertEqual([result.pk for result in self.sq.get_results()], [1, 2, 3]) + + self.sq = SearchQuery(backend=SearchBackend()) + self.sq.add_filter(SQ(name__startswith='daniel1')) + self.assertEqual([result.pk for result in self.sq.get_results()], [1]) + def test_log_query(self): backends.reset_search_queries() self.assertEqual(len(backends.queries), 0) diff --git a/xapian_backend.py b/xapian_backend.py index f6d36bc..6bed2ed 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -480,6 +480,11 @@ class SearchBackend(BaseSearchBackend): Returns a xapian.Query """ + if query_string == '*': + return xapian.Query('') # Match everything + elif query_string == '': + return xapian.Query() # Match nothing + flags = xapian.QueryParser.FLAG_PARTIAL \ | xapian.QueryParser.FLAG_PHRASE \ | xapian.QueryParser.FLAG_BOOLEAN \ @@ -969,10 +974,12 @@ class SearchQuery(BaseSearchQuery): A xapian.Query """ sb = SearchBackend() + term_list = set() for t in sb._database().allterms(): - print t - term_list = [term, 'foo'] - return self._filter_in(term_list, field, is_not) + if t.term.startswith(term.rstrip('*')): + term_list.add(t.term) + + return self._filter_in(list(term_list), field, is_not) def _all_query(self): From 999800e4a82f563081175b8497d2ea02022ab792 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Fri, 4 Dec 2009 16:41:41 -0500 Subject: [PATCH 93/98] __gt is working --- tests/xapian_tests/tests/xapian_backend.py | 16 ++++ tests/xapian_tests/tests/xapian_query.py | 41 ++++---- xapian_backend.py | 104 +++++++++++---------- 3 files changed, 88 insertions(+), 73 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_backend.py b/tests/xapian_tests/tests/xapian_backend.py index bcf63ca..f43082e 100644 --- a/tests/xapian_tests/tests/xapian_backend.py +++ b/tests/xapian_tests/tests/xapian_backend.py @@ -355,6 +355,9 @@ class LiveXapianMockSearchIndex(indexes.SearchIndex): class LiveXapianSearchQueryTestCase(TestCase): + """ + SearchQuery specific tests + """ fixtures = ['initial_data.json'] def setUp(self): @@ -381,6 +384,19 @@ class LiveXapianSearchQueryTestCase(TestCase): self.sq.add_filter(SQ(name__startswith='daniel1')) self.assertEqual([result.pk for result in self.sq.get_results()], [1]) + def test_build_query_gt(self): + self.sq.add_filter(SQ(name__gt='a')) + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(VALUE_RANGE 2 a zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz)') + + def test_build_query_multiple_filter_types(self): + self.sq.add_filter(SQ(content='why')) + # self.sq.add_filter(SQ(pub_date__lte='2009-02-10 01:59:00')) + self.sq.add_filter(SQ(name__gt='david')) + # self.sq.add_filter(SQ(created__lt='2009-02-12 12:13:00')) + # self.sq.add_filter(SQ(title__gte='B')) + self.sq.add_filter(SQ(id__in=[1, 2, 3])) + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((why AND VALUE_RANGE 2 david zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz AND (XID1 OR XID2 OR XID3)))') + def test_log_query(self): backends.reset_search_queries() self.assertEqual(len(backends.queries), 0) diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index 2ef4f11..5d54291 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -17,13 +17,13 @@ class XapianSearchQueryTestCase(TestCase): def setUp(self): super(XapianSearchQueryTestCase, self).setUp() self.sq = SearchQuery(backend=SearchBackend()) - + def tearDown(self): if os.path.exists(settings.HAYSTACK_XAPIAN_PATH): shutil.rmtree(settings.HAYSTACK_XAPIAN_PATH) - + super(XapianSearchQueryTestCase, self).tearDown() - + def test_build_query_all(self): self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query()') @@ -34,15 +34,15 @@ class XapianSearchQueryTestCase(TestCase): def test_build_query_single_word_not(self): self.sq.add_filter(~SQ(content='hello')) self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(( AND_NOT hello))') - + def test_build_query_single_word_field_exact(self): self.sq.add_filter(SQ(foo='hello')) self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(XFOOhello)') - + def test_build_query_single_word_field_exact_not(self): self.sq.add_filter(~SQ(foo='hello')) self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(( AND_NOT XFOOhello))') - + def test_build_query_boolean(self): self.sq.add_filter(SQ(content=True)) self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(true)') @@ -50,7 +50,7 @@ class XapianSearchQueryTestCase(TestCase): def test_build_query_date(self): self.sq.add_filter(SQ(content=datetime.date(2009, 5, 8))) self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(20090508000000)') - + def test_build_query_datetime(self): self.sq.add_filter(SQ(content=datetime.datetime(2009, 5, 8, 11, 28))) self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(20090508112800)') @@ -58,7 +58,7 @@ class XapianSearchQueryTestCase(TestCase): def test_build_query_float(self): self.sq.add_filter(SQ(content=25.52)) self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(25.52)') - + def test_build_query_multiple_words_and(self): self.sq.add_filter(SQ(content='hello')) self.sq.add_filter(SQ(content='world')) @@ -76,7 +76,7 @@ class XapianSearchQueryTestCase(TestCase): def test_build_query_multiple_words_or_not(self): self.sq.add_filter(~SQ(content='hello') | ~SQ(content='world')) self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((( AND_NOT hello) OR ( AND_NOT world)))') - + def test_build_query_multiple_words_mixed(self): self.sq.add_filter(SQ(content='why') | SQ(content='hello')) self.sq.add_filter(~SQ(content='world')) @@ -86,12 +86,12 @@ class XapianSearchQueryTestCase(TestCase): self.sq.add_filter(SQ(foo='hello')) self.sq.add_filter(SQ(bar='world')) self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((XFOOhello AND XBARworld))') - + def test_build_query_multiple_word_field_exact_not(self): self.sq.add_filter(~SQ(foo='hello')) self.sq.add_filter(~SQ(bar='world')) self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((( AND_NOT XFOOhello) AND ( AND_NOT XBARworld)))') - + def test_build_query_phrase(self): self.sq.add_filter(SQ(content='hello world')) self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((hello PHRASE 2 world))') @@ -99,31 +99,22 @@ class XapianSearchQueryTestCase(TestCase): def test_build_query_phrase_not(self): self.sq.add_filter(~SQ(content='hello world')) self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(( AND_NOT (hello PHRASE 2 world)))') - + def test_build_query_boost(self): self.sq.add_filter(SQ(content='hello')) self.sq.add_boost('world', 5) self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((hello OR 5 * world))') - # def test_build_query_multiple_filter_types(self): - # self.sq.add_filter(SQ(content='why')) - # self.sq.add_filter(SQ(pub_date__lte='2009-02-10 01:59:00')) - # self.sq.add_filter(SQ(author__gt='david')) - # self.sq.add_filter(SQ(created__lt='2009-02-12 12:13:00')) - # self.sq.add_filter(SQ(title__gte='B')) - # self.sq.add_filter(SQ(id__in=[1, 2, 3])) - # self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(why AND pub_date:[* TO "2009-02-10 01:59:00"] AND author:{david TO *} AND created:{* TO "2009-02-12 12:13:00"} AND title:[B TO *] AND (id:"1" OR id:"2" OR id:"3"))') - def test_build_query_in_filter_single_words(self): self.sq.add_filter(SQ(content='why')) self.sq.add_filter(SQ(title__in=["Dune", "Jaws"])) self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((why AND (XTITLEdune OR XTITLEjaws)))') - + def test_build_query_not_in_filter_single_words(self): self.sq.add_filter(SQ(content='why')) self.sq.add_filter(~SQ(title__in=["Dune", "Jaws"])) self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((why AND ( AND_NOT (XTITLEdune OR XTITLEjaws))))') - + def test_build_query_in_filter_multiple_words(self): self.sq.add_filter(SQ(content='why')) self.sq.add_filter(SQ(title__in=["A Famous Paper", "An Infamous Article"])) @@ -142,7 +133,7 @@ class XapianSearchQueryTestCase(TestCase): # def test_stem_single_word(self): # self.sq.add_filter(SQ(content='testing')) # self.assertEqual(self.sq.build_query().get_description(), 'Xapian.Query(Ztest)') - # + # def test_clean(self): self.assertEqual(self.sq.clean('hello world'), 'hello world') self.assertEqual(self.sq.clean('hello AND world'), 'hello AND world') @@ -153,6 +144,6 @@ class XapianSearchQueryTestCase(TestCase): self.sq.add_filter(SQ(content='hello')) self.sq.add_model(MockModel) self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((hello AND 0 * XCONTENTTYPEcore.mockmodel))') - + self.sq.add_model(AnotherMockModel) self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((hello AND (0 * XCONTENTTYPEcore.anothermockmodel OR 0 * XCONTENTTYPEcore.mockmodel)))') diff --git a/xapian_backend.py b/xapian_backend.py index 6bed2ed..9011565 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -170,17 +170,17 @@ class SearchBackend(BaseSearchBackend): try: for obj in iterable: document = xapian.Document() - + term_generator = xapian.TermGenerator() term_generator.set_database(database) term_generator.set_stemmer(xapian.Stem(self.language)) if getattr(settings, 'HAYSTACK_INCLUDE_SPELLING', False) is True: term_generator.set_flags(xapian.TermGenerator.FLAG_SPELLING) term_generator.set_document(document) - + document_id = DOCUMENT_ID_TERM_PREFIX + get_identifier(obj) data = index.prepare(obj) - + for field in self.schema: if field['field_name'] in data.keys(): prefix = DOCUMENT_CUSTOM_TERM_PREFIX + field['field_name'].upper() @@ -265,7 +265,7 @@ class SearchBackend(BaseSearchBackend): `narrow_queries` -- Narrow queries (default = None) `spelling_query` -- An optional query to execute spelling suggestion on `limit_to_registered_models` -- Limit returned results to models registered in the current `SearchSite` (default = True) - + Returns: A dictionary with the following keys: `results` -- A list of `SearchResult` @@ -310,26 +310,26 @@ class SearchBackend(BaseSearchBackend): query = xapian.Query( xapian.Query.OP_AND, query, xapian.Query(xapian.Query.OP_OR, list(narrow_queries)) ) - + if limit_to_registered_models: registered_models = self.build_registered_models_list() - + if len(registered_models) > 0: query = xapian.Query( - xapian.Query.OP_AND, query, + xapian.Query.OP_AND, query, xapian.Query( xapian.Query.OP_OR, [ xapian.Query('%s%s' % (DOCUMENT_CT_TERM_PREFIX, model)) for model in registered_models ] ) ) - + enquire = xapian.Enquire(database) enquire.set_query(query) if sort_by: sorter = xapian.MultiValueSorter() - + for sort_field in sort_by: if sort_field.startswith('-'): reverse = True @@ -337,7 +337,7 @@ class SearchBackend(BaseSearchBackend): else: reverse = False # Reverse is inverted in Xapian -- http://trac.xapian.org/ticket/311 sorter.add(self._value_column(sort_field), reverse) - + enquire.set_sort_by_key_then_relevance(sorter, True) results = [] @@ -349,7 +349,7 @@ class SearchBackend(BaseSearchBackend): if not end_offset: end_offset = database.get_doccount() - + matches = enquire.get_mset(start_offset, (end_offset - start_offset)) for match in matches: @@ -379,7 +379,7 @@ class SearchBackend(BaseSearchBackend): } def more_like_this(self, model_instance, additional_query=None, - start_offset=0, end_offset=None, + start_offset=0, end_offset=None, limit_to_registered_models=True, **kwargs): """ Given a model instance, returns a result set of similar documents. @@ -413,18 +413,18 @@ class SearchBackend(BaseSearchBackend): database = self._database() query = xapian.Query(DOCUMENT_ID_TERM_PREFIX + get_identifier(model_instance)) - + enquire = xapian.Enquire(database) enquire.set_query(query) - + rset = xapian.RSet() if not end_offset: end_offset = database.get_doccount() - + for match in enquire.get_mset(0, end_offset): rset.add_document(match.docid) - + query = xapian.Query(xapian.Query.OP_OR, [expand.term for expand in enquire.get_eset(match.document.termlist_count(), rset, XHExpandDecider())] ) @@ -436,7 +436,7 @@ class SearchBackend(BaseSearchBackend): if len(registered_models) > 0: query = xapian.Query( - xapian.Query.OP_AND, query, + xapian.Query.OP_AND, query, xapian.Query( xapian.Query.OP_OR, [ xapian.Query('%s%s' % (DOCUMENT_CT_TERM_PREFIX, model)) for model in registered_models @@ -447,7 +447,7 @@ class SearchBackend(BaseSearchBackend): query = xapian.Query( xapian.Query.OP_AND, query, additional_query ) - + enquire.set_query(query) results = [] @@ -477,14 +477,14 @@ class SearchBackend(BaseSearchBackend): Required arguments: ``query_string`` -- A query string to parse - + Returns a xapian.Query """ if query_string == '*': return xapian.Query('') # Match everything elif query_string == '': return xapian.Query() # Match nothing - + flags = xapian.QueryParser.FLAG_PARTIAL \ | xapian.QueryParser.FLAG_PHRASE \ | xapian.QueryParser.FLAG_BOOLEAN \ @@ -496,7 +496,7 @@ class SearchBackend(BaseSearchBackend): qp.set_stemmer(xapian.Stem(self.language)) qp.set_stemming_strategy(xapian.QueryParser.STEM_SOME) qp.add_boolean_prefix('django_ct', DOCUMENT_CT_TERM_PREFIX) - + for field_dict in self.schema: qp.add_prefix( field_dict['field_name'], @@ -563,17 +563,17 @@ class SearchBackend(BaseSearchBackend): `text` -- The text to be highlighted """ for term in query: - for match in re.findall('[^A-Z]+', term): # Ignore field identifiers + for match in re.findall('[^A-Z]+', term): # Ignore field identifiers match_re = re.compile(match, re.I) content = match_re.sub('<%s>%s' % (tag, term, tag), content) - + return content def _do_field_facets(self, results, field_facets): """ Private method that facets a document by field name. - Fields of type MultiValueField will be faceted on each item in the + Fields of type MultiValueField will be faceted on each item in the (containing) list. Required arguments: @@ -708,7 +708,7 @@ class SearchBackend(BaseSearchBackend): `database` -- The database to check spelling against `query` -- The query to check `spelling_query` -- If not None, this will be checked instead of `query` - + Returns a string with a suggested spelling """ if spelling_query: @@ -721,7 +721,7 @@ class SearchBackend(BaseSearchBackend): for term in query: for match in re.findall('[^A-Z]+', term): # Ignore field identifiers term_list.append(database.get_spelling_suggestion(match)) - + return ' '.join(term_list) def _database(self, writable=False): @@ -736,18 +736,18 @@ class SearchBackend(BaseSearchBackend): """ if writable: self.content_field_name, self.schema = self.build_schema(self.site.all_searchfields()) - + database = xapian.WritableDatabase(settings.HAYSTACK_XAPIAN_PATH, xapian.DB_CREATE_OR_OPEN) database.set_metadata('schema', pickle.dumps(self.schema, pickle.HIGHEST_PROTOCOL)) database.set_metadata('content', pickle.dumps(self.content_field_name, pickle.HIGHEST_PROTOCOL)) else: database = xapian.Database(settings.HAYSTACK_XAPIAN_PATH) - + self.schema = pickle.loads(database.get_metadata('schema')) self.content_field_name = pickle.loads(database.get_metadata('content')) return database - + def _value_column(self, field): """ Private method that returns the column value slot in the database @@ -762,7 +762,7 @@ class SearchBackend(BaseSearchBackend): if field_dict['field_name'] == field: return field_dict['column'] return 0 - + def _multi_value_field(self, field): """ Private method that returns `True` if a field is multi-valued, else @@ -803,12 +803,12 @@ class SearchQuery(BaseSearchQuery): query = xapian.Query('') else: query = self._query_from_search_node(self.query_filter) - + if self.models: subqueries = [ xapian.Query( xapian.Query.OP_SCALE_WEIGHT, xapian.Query('%s%s.%s' % ( - DOCUMENT_CT_TERM_PREFIX, + DOCUMENT_CT_TERM_PREFIX, model._meta.app_label, model._meta.module_name ) ), 0 # Pure boolean sub-query @@ -818,7 +818,7 @@ class SearchQuery(BaseSearchQuery): xapian.Query.OP_AND, query, xapian.Query(xapian.Query.OP_OR, subqueries) ) - + if self.boost: subqueries = [ xapian.Query( @@ -831,7 +831,7 @@ class SearchQuery(BaseSearchQuery): ) return query - + def _query_from_search_node(self, search_node, is_not=False): query_list = [] @@ -839,7 +839,7 @@ class SearchQuery(BaseSearchQuery): if isinstance(child, SearchNode): query_list.append( xapian.Query( - xapian.Query.OP_AND, + xapian.Query.OP_AND, self._query_from_search_node( child, child.negated ) @@ -848,19 +848,19 @@ class SearchQuery(BaseSearchQuery): else: expression, term = child field, filter_type = search_node.split_expression(expression) - + if isinstance(term, (list, tuple)): term = [_marshal_term(t) for t in term] else: term = _marshal_term(term) - + if field == 'content': query_list.append(self._content_field(term, is_not)) else: if filter_type == 'exact': query_list.append(self._filter_exact(term, field, is_not)) elif filter_type == 'gt': - pass + query_list.append(self._filter_gt(term, field, is_not)) elif filter_type == 'gte': pass elif filter_type == 'lt': @@ -871,12 +871,12 @@ class SearchQuery(BaseSearchQuery): query_list.append(self._filter_startswith(term, field, is_not)) elif filter_type == 'in': query_list.append(self._filter_in(term, field, is_not)) - + if search_node.connector == 'OR': return xapian.Query(xapian.Query.OP_OR, query_list) else: return xapian.Query(xapian.Query.OP_AND, query_list) - + def _content_field(self, term, is_not): """ Private method that returns a xapian.Query that searches for `value` @@ -956,7 +956,7 @@ class SearchQuery(BaseSearchQuery): ) ) if is_not: - return xapian.Query(xapian.Query.OP_AND_NOT, self._all_query(), xapian.Query(xapian.Query.OP_OR, query_list)) + return xapian.Query(xapian.Query.OP_AND_NOT, self._all_query(), xapian.Query(xapian.Query.OP_OR, query_list)) else: return xapian.Query(xapian.Query.OP_OR, query_list) @@ -964,12 +964,12 @@ class SearchQuery(BaseSearchQuery): """ Private method that returns a xapian.Query that searches for any term that begins with `term` in a specified `field`. - + Required arguments: ``term`` -- The terms to search for ``field`` -- The field to search ``is_not`` -- Invert the search results - + Returns: A xapian.Query """ @@ -978,10 +978,18 @@ class SearchQuery(BaseSearchQuery): for t in sb._database().allterms(): if t.term.startswith(term.rstrip('*')): term_list.add(t.term) - + return self._filter_in(list(term_list), field, is_not) - - + + def _filter_gt(self, term, field, is_not): + """ + Private methos that returns a xapian.Query that searches for any term + that is greater than `term` in a specified `field`. + """ + vrp = XHValueRangeProcessor(self.backend) + pos, begin, end = vrp('%s:%s' % (field, term), '*') + return xapian.Query(xapian.Query.OP_VALUE_RANGE, pos, begin, end) + def _all_query(self): """ Private method that returns a xapian.Query that returns all documents, @@ -990,7 +998,7 @@ class SearchQuery(BaseSearchQuery): A xapian.Query """ return xapian.Query('') - + def _term_query(self, term, field=None): """ Private method that returns a term based xapian.Query that searches @@ -1010,7 +1018,7 @@ class SearchQuery(BaseSearchQuery): ) else: return xapian.Query(term) - + def _phrase_query(self, term_list, field=None): """ Private method that returns a phrase based xapian.Query that searches From 1fe78fc384b55a25e274de3206326ec6432559ba Mon Sep 17 00:00:00 2001 From: David Sauve Date: Fri, 4 Dec 2009 16:44:36 -0500 Subject: [PATCH 94/98] __lt is working --- tests/xapian_tests/tests/xapian_backend.py | 4 ++++ xapian_backend.py | 13 +++++++++++-- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_backend.py b/tests/xapian_tests/tests/xapian_backend.py index f43082e..2b9c617 100644 --- a/tests/xapian_tests/tests/xapian_backend.py +++ b/tests/xapian_tests/tests/xapian_backend.py @@ -388,6 +388,10 @@ class LiveXapianSearchQueryTestCase(TestCase): self.sq.add_filter(SQ(name__gt='a')) self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(VALUE_RANGE 2 a zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz)') + def test_build_query_lt(self): + self.sq.add_filter(SQ(name__lt='m')) + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(VALUE_RANGE 2 a m)') + def test_build_query_multiple_filter_types(self): self.sq.add_filter(SQ(content='why')) # self.sq.add_filter(SQ(pub_date__lte='2009-02-10 01:59:00')) diff --git a/xapian_backend.py b/xapian_backend.py index 9011565..2bb66c8 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -864,7 +864,7 @@ class SearchQuery(BaseSearchQuery): elif filter_type == 'gte': pass elif filter_type == 'lt': - pass + query_list.append(self._filter_lt(term, field, is_not)) elif filter_type == 'lte': pass elif filter_type == 'startswith': @@ -983,13 +983,22 @@ class SearchQuery(BaseSearchQuery): def _filter_gt(self, term, field, is_not): """ - Private methos that returns a xapian.Query that searches for any term + Private method that returns a xapian.Query that searches for any term that is greater than `term` in a specified `field`. """ vrp = XHValueRangeProcessor(self.backend) pos, begin, end = vrp('%s:%s' % (field, term), '*') return xapian.Query(xapian.Query.OP_VALUE_RANGE, pos, begin, end) + def _filter_lt(self, term, field, is_not): + """ + Private method that returns a xapian.Query that searches for any term + that is less than `term` in a specified `field`. + """ + vrp = XHValueRangeProcessor(self.backend) + pos, begin, end = vrp('%s:' % field, '%s' % term) + return xapian.Query(xapian.Query.OP_VALUE_RANGE, pos, begin, end) + def _all_query(self): """ Private method that returns a xapian.Query that returns all documents, From f1b7c04c1297d5042c87d100b595c2436153e30e Mon Sep 17 00:00:00 2001 From: David Sauve Date: Fri, 4 Dec 2009 20:30:26 -0500 Subject: [PATCH 95/98] Only thing missing now is query_facets --- tests/xapian_tests/tests/xapian_backend.py | 24 ++++++++++++++------ xapian_backend.py | 26 +++++++++++++++++----- 2 files changed, 38 insertions(+), 12 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_backend.py b/tests/xapian_tests/tests/xapian_backend.py index 2b9c617..cd476af 100644 --- a/tests/xapian_tests/tests/xapian_backend.py +++ b/tests/xapian_tests/tests/xapian_backend.py @@ -352,6 +352,8 @@ class LiveXapianMockSearchIndex(indexes.SearchIndex): text = indexes.CharField(document=True, use_template=True) name = indexes.CharField(model_attr='author') pub_date = indexes.DateField(model_attr='pub_date') + created = indexes.DateField() + title = indexes.CharField() class LiveXapianSearchQueryTestCase(TestCase): @@ -385,21 +387,29 @@ class LiveXapianSearchQueryTestCase(TestCase): self.assertEqual([result.pk for result in self.sq.get_results()], [1]) def test_build_query_gt(self): - self.sq.add_filter(SQ(name__gt='a')) - self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(VALUE_RANGE 2 a zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz)') + self.sq.add_filter(SQ(name__gt='m')) + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(( AND_NOT VALUE_RANGE 3 a m))') + + def test_build_query_gte(self): + self.sq.add_filter(SQ(name__gte='m')) + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(VALUE_RANGE 3 m zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz)') def test_build_query_lt(self): self.sq.add_filter(SQ(name__lt='m')) - self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(VALUE_RANGE 2 a m)') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(( AND_NOT VALUE_RANGE 3 m zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz))') + + def test_build_query_lte(self): + self.sq.add_filter(SQ(name__lte='m')) + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(VALUE_RANGE 3 a m)') def test_build_query_multiple_filter_types(self): self.sq.add_filter(SQ(content='why')) - # self.sq.add_filter(SQ(pub_date__lte='2009-02-10 01:59:00')) + self.sq.add_filter(SQ(pub_date__lte=datetime.datetime(2009, 2, 10, 1, 59, 0))) self.sq.add_filter(SQ(name__gt='david')) - # self.sq.add_filter(SQ(created__lt='2009-02-12 12:13:00')) - # self.sq.add_filter(SQ(title__gte='B')) + self.sq.add_filter(SQ(created__lt=datetime.datetime(2009, 2, 12, 12, 13, 0))) + self.sq.add_filter(SQ(title__gte='B')) self.sq.add_filter(SQ(id__in=[1, 2, 3])) - self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((why AND VALUE_RANGE 2 david zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz AND (XID1 OR XID2 OR XID3)))') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((why AND VALUE_RANGE 2 00010101000000 20090210015900 AND ( AND_NOT VALUE_RANGE 3 a david) AND ( AND_NOT VALUE_RANGE 4 20090212121300 99990101000000) AND VALUE_RANGE 1 b zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz AND (XID1 OR XID2 OR XID3)))') def test_log_query(self): backends.reset_search_queries() diff --git a/xapian_backend.py b/xapian_backend.py index 2bb66c8..3e27652 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -862,11 +862,11 @@ class SearchQuery(BaseSearchQuery): elif filter_type == 'gt': query_list.append(self._filter_gt(term, field, is_not)) elif filter_type == 'gte': - pass + query_list.append(self._filter_gte(term, field, is_not)) elif filter_type == 'lt': query_list.append(self._filter_lt(term, field, is_not)) elif filter_type == 'lte': - pass + query_list.append(self._filter_lte(term, field, is_not)) elif filter_type == 'startswith': query_list.append(self._filter_startswith(term, field, is_not)) elif filter_type == 'in': @@ -982,21 +982,37 @@ class SearchQuery(BaseSearchQuery): return self._filter_in(list(term_list), field, is_not) def _filter_gt(self, term, field, is_not): + return self._filter_lte(term, field, is_not=(is_not != True)) + + def _filter_lt(self, term, field, is_not): + return self._filter_gte(term, field, is_not=(is_not != True)) + + def _filter_gte(self, term, field, is_not): """ Private method that returns a xapian.Query that searches for any term that is greater than `term` in a specified `field`. """ vrp = XHValueRangeProcessor(self.backend) - pos, begin, end = vrp('%s:%s' % (field, term), '*') + pos, begin, end = vrp('%s:%s' % (field, _marshal_value(term)), '*') + if is_not: + return xapian.Query(xapian.Query.OP_AND_NOT, + self._all_query(), + xapian.Query(xapian.Query.OP_VALUE_RANGE, pos, begin, end) + ) return xapian.Query(xapian.Query.OP_VALUE_RANGE, pos, begin, end) - def _filter_lt(self, term, field, is_not): + def _filter_lte(self, term, field, is_not): """ Private method that returns a xapian.Query that searches for any term that is less than `term` in a specified `field`. """ vrp = XHValueRangeProcessor(self.backend) - pos, begin, end = vrp('%s:' % field, '%s' % term) + pos, begin, end = vrp('%s:' % field, '%s' % _marshal_value(term)) + if is_not: + return xapian.Query(xapian.Query.OP_AND_NOT, + self._all_query(), + xapian.Query(xapian.Query.OP_VALUE_RANGE, pos, begin, end) + ) return xapian.Query(xapian.Query.OP_VALUE_RANGE, pos, begin, end) def _all_query(self): From 3752844e4a56bc033d56ccd1ea064a48e0bf50c3 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Fri, 4 Dec 2009 20:45:36 -0500 Subject: [PATCH 96/98] Fix for date facet when gap by month amount is larger than 1 --- xapian_backend.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/xapian_backend.py b/xapian_backend.py index 3e27652..c4477a5 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -640,9 +640,10 @@ class SearchBackend(BaseSearchBackend): year=date_range.year + int(gap_value) ) elif gap_type == 'month': - if date_range.month == 12: + if date_range.month + int(gap_value) > 12: date_range = date_range.replace( - month=1, year=date_range.year + int(gap_value) + month=((date_range.month + int(gap_value)) % 12), + year=(date_range.year + (date_range.month + int(gap_value)) / 12) ) else: date_range = date_range.replace( From 72134e096b1c07e2d87cd971b810363fe83e6c31 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Sat, 5 Dec 2009 10:43:52 -0500 Subject: [PATCH 97/98] Query facets working again and reworked narrow to take a query_string instead of xapian.Query. This should be easier to use. --- tests/xapian_tests/tests/xapian_backend.py | 20 ++++++++++---------- xapian_backend.py | 8 +++++--- 2 files changed, 15 insertions(+), 13 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_backend.py b/tests/xapian_tests/tests/xapian_backend.py index cd476af..377fa83 100644 --- a/tests/xapian_tests/tests/xapian_backend.py +++ b/tests/xapian_tests/tests/xapian_backend.py @@ -220,21 +220,21 @@ class XapianSearchBackendTestCase(TestCase): ('2009-02-01T00:00:00', 0) ]) - # def test_query_facets(self): - # self.backend.update(self.index, self.sample_objs) - # self.assertEqual(len(self.xapian_search('')), 3) - # - # self.assertEqual(self.backend.search(xapian.Query(), query_facets={'name': 'da*', {'hits': 0, 'results': []}) - # results = self.backend.search(xapian.Query('index'), query_facets={'name': 'da*'}) - # self.assertEqual(results['hits'], 3) - # self.assertEqual(results['facets']['queries']['name'], ('da*', 3)) + def test_query_facets(self): + self.backend.update(self.index, self.sample_objs) + self.assertEqual(len(self.xapian_search('')), 3) + + self.assertEqual(self.backend.search(xapian.Query(), query_facets={'name': 'da*'}), {'hits': 0, 'results': []}) + results = self.backend.search(xapian.Query('indexed'), query_facets={'name': 'da*'}) + self.assertEqual(results['hits'], 3) + self.assertEqual(results['facets']['queries']['name'], ('da*', 3)) def test_narrow_queries(self): self.backend.update(self.index, self.sample_objs) self.assertEqual(len(self.xapian_search('')), 3) - self.assertEqual(self.backend.search(xapian.Query(), narrow_queries=set([xapian.Query('XNAMEdavid1')])), {'hits': 0, 'results': []}) - results = self.backend.search(xapian.Query('indexed'), narrow_queries=set([xapian.Query('XNAMEdavid1')])) + self.assertEqual(self.backend.search(xapian.Query(), narrow_queries=set(['name:david1'])), {'hits': 0, 'results': []}) + results = self.backend.search(xapian.Query('indexed'), narrow_queries=set(['name:david1'])) self.assertEqual(results['hits'], 1) def test_highlight(self): diff --git a/xapian_backend.py b/xapian_backend.py index c4477a5..8cdf77b 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -308,7 +308,9 @@ class SearchBackend(BaseSearchBackend): if narrow_queries is not None: query = xapian.Query( - xapian.Query.OP_AND, query, xapian.Query(xapian.Query.OP_OR, list(narrow_queries)) + xapian.Query.OP_AND, query, xapian.Query( + xapian.Query.OP_OR, [self.parse_query(narrow_query) for narrow_query in narrow_queries] + ) ) if limit_to_registered_models: @@ -696,8 +698,8 @@ class SearchBackend(BaseSearchBackend): facet_dict = {} for field, query in query_facets.iteritems(): - facet_dict[field] = (query, self.search(query)['hits']) - + facet_dict[field] = (query, self.search(self.parse_query(query))['hits']) + return facet_dict def _do_spelling_suggestion(self, database, query, spelling_query): From 1ec4fdf7ab43691328c7a9205ab43ca6cddfa4e5 Mon Sep 17 00:00:00 2001 From: David Sauve Date: Sat, 5 Dec 2009 11:32:29 -0500 Subject: [PATCH 98/98] Added stemming support --- tests/xapian_tests/tests/xapian_backend.py | 8 ++-- tests/xapian_tests/tests/xapian_query.py | 50 ++++++++++------------ xapian_backend.py | 24 ++++++++--- 3 files changed, 45 insertions(+), 37 deletions(-) diff --git a/tests/xapian_tests/tests/xapian_backend.py b/tests/xapian_tests/tests/xapian_backend.py index 377fa83..416da16 100644 --- a/tests/xapian_tests/tests/xapian_backend.py +++ b/tests/xapian_tests/tests/xapian_backend.py @@ -409,7 +409,7 @@ class LiveXapianSearchQueryTestCase(TestCase): self.sq.add_filter(SQ(created__lt=datetime.datetime(2009, 2, 12, 12, 13, 0))) self.sq.add_filter(SQ(title__gte='B')) self.sq.add_filter(SQ(id__in=[1, 2, 3])) - self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((why AND VALUE_RANGE 2 00010101000000 20090210015900 AND ( AND_NOT VALUE_RANGE 3 a david) AND ( AND_NOT VALUE_RANGE 4 20090212121300 99990101000000) AND VALUE_RANGE 1 b zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz AND (XID1 OR XID2 OR XID3)))') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(((Zwhy OR why) AND VALUE_RANGE 2 00010101000000 20090210015900 AND ( AND_NOT VALUE_RANGE 3 a david) AND ( AND_NOT VALUE_RANGE 4 20090212121300 99990101000000) AND VALUE_RANGE 1 b zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz AND (ZXID1 OR XID1 OR ZXID2 OR XID2 OR ZXID3 OR XID3)))') def test_log_query(self): backends.reset_search_queries() @@ -428,7 +428,7 @@ class LiveXapianSearchQueryTestCase(TestCase): self.sq.add_filter(SQ(name='bar')) len(self.sq.get_results()) self.assertEqual(len(backends.queries), 1) - self.assertEqual(backends.queries[0]['query_string'].get_description(), 'Xapian::Query(XNAMEbar)') + self.assertEqual(backends.queries[0]['query_string'].get_description(), u'Xapian::Query((ZXNAMEbar OR XNAMEbar))') # And again, for good measure. self.sq = SearchQuery(backend=SearchBackend()) @@ -436,8 +436,8 @@ class LiveXapianSearchQueryTestCase(TestCase): self.sq.add_filter(SQ(text='moof')) len(self.sq.get_results()) self.assertEqual(len(backends.queries), 2) - self.assertEqual(backends.queries[0]['query_string'].get_description(), u'Xapian::Query(XNAMEbar)') - self.assertEqual(backends.queries[1]['query_string'].get_description(), u'Xapian::Query((XNAMEbar AND XTEXTmoof))') + self.assertEqual(backends.queries[0]['query_string'].get_description(), u'Xapian::Query((ZXNAMEbar OR XNAMEbar))') + self.assertEqual(backends.queries[1]['query_string'].get_description(), u'Xapian::Query(((ZXNAMEbar OR XNAMEbar) AND (ZXTEXTmoof OR XTEXTmoof)))') # Restore. settings.DEBUG = old_debug diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py index 5d54291..d615e4a 100644 --- a/tests/xapian_tests/tests/xapian_query.py +++ b/tests/xapian_tests/tests/xapian_query.py @@ -29,68 +29,68 @@ class XapianSearchQueryTestCase(TestCase): def test_build_query_single_word(self): self.sq.add_filter(SQ(content='hello')) - self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(hello)') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((Zhello OR hello))') def test_build_query_single_word_not(self): self.sq.add_filter(~SQ(content='hello')) - self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(( AND_NOT hello))') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(( AND_NOT (Zhello OR hello)))') def test_build_query_single_word_field_exact(self): self.sq.add_filter(SQ(foo='hello')) - self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(XFOOhello)') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((ZXFOOhello OR XFOOhello))') def test_build_query_single_word_field_exact_not(self): self.sq.add_filter(~SQ(foo='hello')) - self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(( AND_NOT XFOOhello))') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(( AND_NOT (ZXFOOhello OR XFOOhello)))') def test_build_query_boolean(self): self.sq.add_filter(SQ(content=True)) - self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(true)') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((Ztrue OR true))') def test_build_query_date(self): self.sq.add_filter(SQ(content=datetime.date(2009, 5, 8))) - self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(20090508000000)') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((Z20090508000000 OR 20090508000000))') def test_build_query_datetime(self): self.sq.add_filter(SQ(content=datetime.datetime(2009, 5, 8, 11, 28))) - self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(20090508112800)') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((Z20090508112800 OR 20090508112800))') def test_build_query_float(self): self.sq.add_filter(SQ(content=25.52)) - self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(25.52)') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((Z25.52 OR 25.52))') def test_build_query_multiple_words_and(self): self.sq.add_filter(SQ(content='hello')) self.sq.add_filter(SQ(content='world')) - self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((hello AND world))') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(((Zhello OR hello) AND (Zworld OR world)))') def test_build_query_multiple_words_not(self): self.sq.add_filter(~SQ(content='hello')) self.sq.add_filter(~SQ(content='world')) - self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((( AND_NOT hello) AND ( AND_NOT world)))') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((( AND_NOT (Zhello OR hello)) AND ( AND_NOT (Zworld OR world))))') def test_build_query_multiple_words_or(self): self.sq.add_filter(SQ(content='hello') | SQ(content='world')) - self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((hello OR world))') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((Zhello OR hello OR Zworld OR world))') def test_build_query_multiple_words_or_not(self): self.sq.add_filter(~SQ(content='hello') | ~SQ(content='world')) - self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((( AND_NOT hello) OR ( AND_NOT world)))') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((( AND_NOT (Zhello OR hello)) OR ( AND_NOT (Zworld OR world))))') def test_build_query_multiple_words_mixed(self): self.sq.add_filter(SQ(content='why') | SQ(content='hello')) self.sq.add_filter(~SQ(content='world')) - self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(((why OR hello) AND ( AND_NOT world)))') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(((Zwhy OR why OR Zhello OR hello) AND ( AND_NOT (Zworld OR world))))') def test_build_query_multiple_word_field_exact(self): self.sq.add_filter(SQ(foo='hello')) self.sq.add_filter(SQ(bar='world')) - self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((XFOOhello AND XBARworld))') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(((ZXFOOhello OR XFOOhello) AND (ZXBARworld OR XBARworld)))') def test_build_query_multiple_word_field_exact_not(self): self.sq.add_filter(~SQ(foo='hello')) self.sq.add_filter(~SQ(bar='world')) - self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((( AND_NOT XFOOhello) AND ( AND_NOT XBARworld)))') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((( AND_NOT (ZXFOOhello OR XFOOhello)) AND ( AND_NOT (ZXBARworld OR XBARworld))))') def test_build_query_phrase(self): self.sq.add_filter(SQ(content='hello world')) @@ -103,37 +103,33 @@ class XapianSearchQueryTestCase(TestCase): def test_build_query_boost(self): self.sq.add_filter(SQ(content='hello')) self.sq.add_boost('world', 5) - self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((hello OR 5 * world))') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((Zhello OR hello OR 5 * world))') def test_build_query_in_filter_single_words(self): self.sq.add_filter(SQ(content='why')) self.sq.add_filter(SQ(title__in=["Dune", "Jaws"])) - self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((why AND (XTITLEdune OR XTITLEjaws)))') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(((Zwhy OR why) AND (ZXTITLEdune OR XTITLEdune OR ZXTITLEjaw OR XTITLEjaws)))') def test_build_query_not_in_filter_single_words(self): self.sq.add_filter(SQ(content='why')) self.sq.add_filter(~SQ(title__in=["Dune", "Jaws"])) - self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((why AND ( AND_NOT (XTITLEdune OR XTITLEjaws))))') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(((Zwhy OR why) AND ( AND_NOT (ZXTITLEdune OR XTITLEdune OR ZXTITLEjaw OR XTITLEjaws))))') def test_build_query_in_filter_multiple_words(self): self.sq.add_filter(SQ(content='why')) self.sq.add_filter(SQ(title__in=["A Famous Paper", "An Infamous Article"])) - self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((why AND ((XTITLEa PHRASE 3 XTITLEfamous PHRASE 3 XTITLEpaper) OR (XTITLEan PHRASE 3 XTITLEinfamous PHRASE 3 XTITLEarticle))))') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(((Zwhy OR why) AND ((XTITLEa PHRASE 3 XTITLEfamous PHRASE 3 XTITLEpaper) OR (XTITLEan PHRASE 3 XTITLEinfamous PHRASE 3 XTITLEarticle))))') def test_build_query_not_in_filter_multiple_words(self): self.sq.add_filter(SQ(content='why')) self.sq.add_filter(~SQ(title__in=["A Famous Paper", "An Infamous Article"])) - self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((why AND ( AND_NOT ((XTITLEa PHRASE 3 XTITLEfamous PHRASE 3 XTITLEpaper) OR (XTITLEan PHRASE 3 XTITLEinfamous PHRASE 3 XTITLEarticle)))))') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(((Zwhy OR why) AND ( AND_NOT ((XTITLEa PHRASE 3 XTITLEfamous PHRASE 3 XTITLEpaper) OR (XTITLEan PHRASE 3 XTITLEinfamous PHRASE 3 XTITLEarticle)))))') def test_build_query_in_filter_datetime(self): self.sq.add_filter(SQ(content='why')) self.sq.add_filter(SQ(pub_date__in=[datetime.datetime(2009, 7, 6, 1, 56, 21)])) - self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((why AND XPUB_DATE20090706015621))') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(((Zwhy OR why) AND (ZXPUB_DATE20090706015621 OR XPUB_DATE20090706015621)))') - # def test_stem_single_word(self): - # self.sq.add_filter(SQ(content='testing')) - # self.assertEqual(self.sq.build_query().get_description(), 'Xapian.Query(Ztest)') - # def test_clean(self): self.assertEqual(self.sq.clean('hello world'), 'hello world') self.assertEqual(self.sq.clean('hello AND world'), 'hello AND world') @@ -143,7 +139,7 @@ class XapianSearchQueryTestCase(TestCase): def test_build_query_with_models(self): self.sq.add_filter(SQ(content='hello')) self.sq.add_model(MockModel) - self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((hello AND 0 * XCONTENTTYPEcore.mockmodel))') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(((Zhello OR hello) AND 0 * XCONTENTTYPEcore.mockmodel))') self.sq.add_model(AnotherMockModel) - self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query((hello AND (0 * XCONTENTTYPEcore.anothermockmodel OR 0 * XCONTENTTYPEcore.mockmodel)))') + self.assertEqual(self.sq.build_query().get_description(), u'Xapian::Query(((Zhello OR hello) AND (0 * XCONTENTTYPEcore.anothermockmodel OR 0 * XCONTENTTYPEcore.mockmodel)))') diff --git a/xapian_backend.py b/xapian_backend.py index 8cdf77b..5079fe2 100755 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -720,12 +720,12 @@ class SearchBackend(BaseSearchBackend): else: return database.get_spelling_suggestion(spelling_query) - term_list = [] + term_set = set() for term in query: for match in re.findall('[^A-Z]+', term): # Ignore field identifiers - term_list.append(database.get_spelling_suggestion(match)) + term_set.add(database.get_spelling_suggestion(match)) - return ' '.join(term_list) + return ' '.join(term_set) def _database(self, writable=False): """ @@ -1039,13 +1039,25 @@ class SearchQuery(BaseSearchQuery): Returns: A xapian.Query """ + stem = xapian.Stem(self.backend.language) if field: - return xapian.Query('%s%s%s' % ( - DOCUMENT_CUSTOM_TERM_PREFIX, field.upper(), term + return xapian.Query( + xapian.Query.OP_OR, + xapian.Query('Z%s%s%s' % ( + DOCUMENT_CUSTOM_TERM_PREFIX, field.upper(), stem(term) + ) + ), + xapian.Query('%s%s%s' % ( + DOCUMENT_CUSTOM_TERM_PREFIX, field.upper(), term + ) ) ) else: - return xapian.Query(term) + return xapian.Query( + xapian.Query.OP_OR, + xapian.Query('Z%s' % term), + xapian.Query(term) + ) def _phrase_query(self, term_list, field=None): """