Commit 2f19b7ef by Oleg Marshev

Add highlighting.

parent 262e5bc0
......@@ -122,6 +122,11 @@ class NoteMappingType(MappingType, Indexable):
for k, v in item.items():
if k != 'ranges' and isinstance(v, list) and len(v) > 0:
data[i][k] = v[0]
# Substitute the value of text field by highlighted result.
if len(item.es_meta.highlight) and k == 'text':
data[i][k] = item.es_meta.highlight['text'][0]
return data
note_searcher = NoteMappingType.search()
......@@ -328,6 +328,21 @@ class AnnotationViewTests(BaseAnnotationViewTests):
self.assertEqual(len(results['rows']), 1)
self.assertEqual(results['rows'][0]['text'], 'Second note')
def test_search_highlight(self):
"""
Tests highlighting.
"""
self._create_annotation(text=u'First note')
note_2 = self._create_annotation(text=u'Second note')
results = self._get_search_results()
self.assertEqual(results['total'], 2)
results = self._get_search_results(text="first", highlight=True)
self.assertEqual(results['total'], 1)
self.assertEqual(len(results['rows']), 1)
self.assertEqual(results['rows'][0]['text'], '<span>First</span> note')
def test_search_ordering(self):
"""
Tests ordering of search results.
......
......@@ -25,9 +25,21 @@ class AnnotationSearchView(APIView):
params = {}
for k, v in self.request.QUERY_PARAMS.dict().items():
params[k] = v.lower()
results = NoteMappingType.process_result(
list(note_searcher.filter(**params).order_by("-created").values_dict("_source"))
)
if params.get('highlight'):
params.pop('highlight')
results = NoteMappingType.process_result(
list(
note_searcher.query(**params).order_by("-created").values_dict("_source") \
.highlight("text", pre_tags=['<span>'], post_tags=['</span>'])
)
)
else:
results = NoteMappingType.process_result(
list(note_searcher.filter(**params).order_by("-created").values_dict("_source"))
)
return Response({'total': len(results), 'rows': results})
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment