Ejemplo n.º 1
0
 def test_group_terms(self):
     """:meth:`._group_terms` groups terms using logical precedence."""
     query = AdvancedQuery(terms=FieldedSearchList([
         FieldedSearchTerm(operator=None, field='title', term='muon'),
         FieldedSearchTerm(operator='OR', field='title', term='gluon'),
         FieldedSearchTerm(operator='NOT', field='title', term='foo'),
         FieldedSearchTerm(operator='AND', field='title', term='boson'),
     ]))
     expected = (
         FieldedSearchTerm(operator=None, field='title', term='muon'),
         'OR',
         (
           (
             FieldedSearchTerm(operator='OR', field='title', term='gluon'),
             'NOT',
             FieldedSearchTerm(operator='NOT', field='title', term='foo')
           ),
           'AND',
           FieldedSearchTerm(operator='AND', field='title', term='boson')
         )
     )
     try:
         terms = advanced._group_terms(query)
     except AssertionError:
         self.fail('Should result in a single group')
     self.assertEqual(expected, terms)
Ejemplo n.º 2
0
 def test_group_terms(self):
     """:meth:`._group_terms` groups terms using logical precedence."""
     query = AdvancedQuery(terms=FieldedSearchList([
         FieldedSearchTerm(operator=None, field="title", term="muon"),
         FieldedSearchTerm(operator="OR", field="title", term="gluon"),
         FieldedSearchTerm(operator="NOT", field="title", term="foo"),
         FieldedSearchTerm(operator="AND", field="title", term="boson"),
     ]))
     expected = (
         FieldedSearchTerm(operator=None, field="title", term="muon"),
         "OR",
         (
             (
                 FieldedSearchTerm(operator="OR",
                                   field="title",
                                   term="gluon"),
                 "NOT",
                 FieldedSearchTerm(operator="NOT",
                                   field="title",
                                   term="foo"),
             ),
             "AND",
             FieldedSearchTerm(operator="AND", field="title", term="boson"),
         ),
     )
     try:
         terms = advanced._group_terms(query)
     except AssertionError:
         self.fail("Should result in a single group")
     self.assertEqual(expected, terms)
Ejemplo n.º 3
0
def _update_query_with_terms(q: AdvancedQuery, terms_data: list) \
        -> AdvancedQuery:
    q.terms = FieldedSearchList([
        FieldedSearchTerm(**term)  # type: ignore
        for term in terms_data if term['term']
    ])
    return q
Ejemplo n.º 4
0
def _get_fielded_terms(
    params: MultiDict,
    query_terms: List,
    operators: Optional[Dict[str, Any]] = None,
) -> Optional[FieldedSearchList]:
    if operators is None:
        operators = defaultdict(default_factory=lambda: "AND")
    terms = FieldedSearchList()
    for field, _ in Query.SUPPORTED_FIELDS:
        values = params.getlist(field)
        for value in values:
            query_terms.append({"parameter": field, "value": value})
            terms.append(
                FieldedSearchTerm(  # type: ignore
                    operator=operators[field],
                    field=field,
                    term=value))
    if not terms:
        return None
    return terms
Ejemplo n.º 5
0
    def test_advanced_query(self, mock_Elasticsearch, mock_Search):
        """:class:`.index.search` supports :class:`AdvancedQuery`."""
        mock_results = mock.MagicMock()
        mock_results.__getitem__.return_value = {'total': 53}
        rdata = dict(authors=[{'full_name': 'N. Ame'}],
                     owners=[{'full_name': 'N. Ame'}],
                     submitter={'full_name': 'N. Ame'},
                     paper_id='1234.56789')
        mock_result = mock.MagicMock(_d_=rdata, **rdata)
        mock_result.meta.score = 1
        mock_results.__iter__.return_value = [mock_result]
        mock_Search.execute.return_value = mock_results

        # Support the chaining API for py-ES.
        mock_Search.return_value = mock_Search
        mock_Search.filter.return_value = mock_Search
        mock_Search.highlight.return_value = mock_Search
        mock_Search.highlight_options.return_value = mock_Search
        mock_Search.query.return_value = mock_Search
        mock_Search.sort.return_value = mock_Search
        mock_Search.__getitem__.return_value = mock_Search

        query = AdvancedQuery(
            order='relevance',
            size=10,
            date_range=DateRange(
                start_date=datetime.now() - timedelta(days=5),
                end_date=datetime.now()
            ),
            classification=ClassificationList([
                Classification(
                    group={'id': 'physics'},
                    archive={'id': 'physics'},
                    category={'id': 'hep-th'}
                )
            ]),
            terms=FieldedSearchList([
                FieldedSearchTerm(operator='AND', field='title', term='foo'),
                FieldedSearchTerm(operator='AND', field='author', term='joe'),
                FieldedSearchTerm(operator='OR', field='abstract', term='hmm'),
                FieldedSearchTerm(operator='NOT', field='comments', term='eh'),
                FieldedSearchTerm(operator='AND', field='journal_ref',
                                  term='jref (1999) 1:2-3'),
                FieldedSearchTerm(operator='AND', field='acm_class',
                                  term='abc123'),
                FieldedSearchTerm(operator='AND', field='msc_class',
                                  term='abc123'),
                FieldedSearchTerm(operator='OR', field='report_num',
                                  term='abc123'),
                FieldedSearchTerm(operator='OR', field='doi',
                                  term='10.01234/56789'),
                FieldedSearchTerm(operator='OR', field='orcid',
                                  term='0000-0000-0000-0000'),
                FieldedSearchTerm(operator='OR', field='author_id',
                                  term='Bloggs_J'),
            ])
        )
        document_set = index.SearchSession.search(query)
        # self.assertIsInstance(document_set, DocumentSet)
        self.assertEqual(document_set['metadata']['start'], 0)
        self.assertEqual(document_set['metadata']['total'], 53)
        self.assertEqual(document_set['metadata']['current_page'], 1)
        self.assertEqual(document_set['metadata']['total_pages'], 6)
        self.assertEqual(document_set['metadata']['size'], 10)
        self.assertEqual(len(document_set['results']), 1)
Ejemplo n.º 6
0
    def test_advanced_query(self, mock_Elasticsearch, mock_Search):
        """:class:`.index.search` supports :class:`AdvancedQuery`."""
        mock_results = mock.MagicMock()
        mock_results.__getitem__.return_value = {"total": 53}
        rdata = mock_rdata()
        mock_result = mock.MagicMock(_d_=rdata, **rdata)
        mock_result.meta.score = 1
        mock_results.__iter__.return_value = [mock_result]
        mock_Search.execute.return_value = mock_results

        # Support the chaining API for py-ES.
        mock_Search.return_value = mock_Search
        mock_Search.filter.return_value = mock_Search
        mock_Search.highlight.return_value = mock_Search
        mock_Search.highlight_options.return_value = mock_Search
        mock_Search.query.return_value = mock_Search
        mock_Search.sort.return_value = mock_Search
        mock_Search.__getitem__.return_value = mock_Search

        query = AdvancedQuery(
            order="relevance",
            size=10,
            date_range=DateRange(
                start_date=datetime.now() - timedelta(days=5),
                end_date=datetime.now(),
            ),
            classification=ClassificationList([
                Classification(
                    group={"id": "physics"},
                    archive={"id": "physics"},
                    category={"id": "hep-th"},
                )
            ]),
            terms=FieldedSearchList([
                FieldedSearchTerm(operator="AND", field="title", term="foo"),
                FieldedSearchTerm(operator="AND", field="author", term="joe"),
                FieldedSearchTerm(operator="OR", field="abstract", term="hmm"),
                FieldedSearchTerm(operator="NOT", field="comments", term="eh"),
                FieldedSearchTerm(
                    operator="AND",
                    field="journal_ref",
                    term="jref (1999) 1:2-3",
                ),
                FieldedSearchTerm(operator="AND",
                                  field="acm_class",
                                  term="abc123"),
                FieldedSearchTerm(operator="AND",
                                  field="msc_class",
                                  term="abc123"),
                FieldedSearchTerm(operator="OR",
                                  field="report_num",
                                  term="abc123"),
                FieldedSearchTerm(operator="OR",
                                  field="doi",
                                  term="10.01234/56789"),
                FieldedSearchTerm(
                    operator="OR",
                    field="orcid",
                    term="0000-0000-0000-0000",
                ),
                FieldedSearchTerm(operator="OR",
                                  field="author_id",
                                  term="Bloggs_J"),
            ]),
        )
        document_set = index.SearchSession.search(query)
        # self.assertIsInstance(document_set, DocumentSet)
        self.assertEqual(document_set["metadata"]["start"], 0)
        self.assertEqual(document_set["metadata"]["total_results"], 53)
        self.assertEqual(document_set["metadata"]["current_page"], 1)
        self.assertEqual(document_set["metadata"]["total_pages"], 6)
        self.assertEqual(document_set["metadata"]["size"], 10)
        self.assertEqual(len(document_set["results"]), 1)