def test_add(self):
        """ Test adding a result to the result set.

        Adding a thread to the result set with it's score should save
        the thread in the result set.
        """
        thread = create_thread()
        result_set = SearchResultSet()
        result_set.add(thread, 0)

        self.assertEqual((thread, 0), result_set[0])
    def test_add_default_score(self):
        """ Test adding a result to the result set with no score.

        Adding a thread to the result set and not specifying a score
        should set the result's score to 0.
        """
        thread = create_thread()
        result_set = SearchResultSet()
        result_set.add(thread)

        self.assertEqual((thread, 0), result_set[0])
    def search(self, query_string):
        """ Search all thread instances for the given query string """
        threads = models.Thread.objects.filter(
            reduce(
                lambda q, f: q & Q(title__icontains=f),
                query_string.split(),
                Q()))

        result_set = SearchResultSet()
        for thread in threads:
            result_set.add(thread)

        return result_set
    def test_get_sorted(self):
        """ Test getting the sorted results.

        The results should be ordered by score, descending.
        """
        result_set = SearchResultSet()
        result_set.results = [
            (None, 1),
            (None, 0),
            (None, 3),
        ]

        expected = [
            (None, 3),
            (None, 1),
            (None, 0),
        ]

        self.assertEqual(expected, result_set.get_sorted())
    def search(self, query_string):
        """ Search for the given query string """
        body = {
            'query': {
                'bool': {
                    'should': [
                        {
                            'match': {
                                'title': query_string,
                            },
                        },
                        {
                            'match': {
                                'body': query_string,
                            },
                        },
                    ]
                }
            }
        }

        search_results = self.es.search(
            index=self.index,
            doc_type='message,thread',
            body=body)

        hits = search_results.get('hits').get('hits')

        result_set = SearchResultSet()

        for hit in hits:
            id = hit.get('_id')
            doc_type = hit.get('_type')

            if doc_type == 'thread':
                obj = models.Thread.objects.get(id=id)
            elif doc_type == 'message':
                obj = models.Message.objects.get(id=id)

            score = hit.get('_score')
            result_set.add(obj, score)

        return result_set