Skip to content

Commit 3bec78d

Browse files
[DAGE-20] changed tests and _search method in both elastic and solr
1 parent fbe6e38 commit 3bec78d

4 files changed

Lines changed: 127 additions & 50 deletions

File tree

rre-dataset-generator/src/search_engine/elasticsearch_search_engine.py

Lines changed: 39 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
from src.search_engine.search_engine_base import BaseSearchEngine
99
from src.model.document import Document
10+
from src.utils import clean_text
1011

1112
import logging
1213
log = logging.getLogger(__name__)
@@ -114,11 +115,41 @@ def _search(self, payload: Dict[str, Any]) -> List[Document]:
114115
raise
115116

116117
data = response.json()
117-
raw_docs = (data.get('hits') or {}).get('hits') or []
118-
reformat_raw_doc = []
119-
for doc in raw_docs:
120-
clean_doc = dict()
121-
clean_doc['id'] = doc[self.UNIQUE_KEY]
122-
clean_doc['fields'] = doc['_source']
123-
reformat_raw_doc.append(Document(**clean_doc))
124-
return reformat_raw_doc
118+
hits = (data.get('hits') or {}).get('hits') or []
119+
result = []
120+
for hit in hits:
121+
source = hit.get("_source", {})
122+
doc_id = source.get("id", hit.get(self.UNIQUE_KEY))
123+
124+
fields = {
125+
key: self._normalize(value)
126+
for key, value in source.items()
127+
if key != "id"
128+
}
129+
130+
result.append(Document(id=doc_id, fields=fields))
131+
return result
132+
133+
@staticmethod
134+
def _normalize(value: Any) -> List[str]:
135+
"""Normalize a field value into a list of cleaned strings or throws an exception."""
136+
try:
137+
if value is None:
138+
return []
139+
140+
if isinstance(value, str):
141+
return [clean_text(value)]
142+
143+
if isinstance(value, list):
144+
return [clean_text(v) if isinstance(v, str) else str(v) for v in value]
145+
146+
if isinstance(value, dict):
147+
cleaned_dict = {
148+
k: clean_text(v) if isinstance(v, str) else v
149+
for k, v in value.items()
150+
}
151+
return [json.dumps(cleaned_dict)]
152+
153+
return [str(value)]
154+
except Exception as e:
155+
raise ValueError(f"Failed to normalize value: {value}") from e

rre-dataset-generator/src/search_engine/solr_search_engine.py

Lines changed: 36 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -127,24 +127,39 @@ def _search(self, payload: Dict[str, Any]) -> List[Document]:
127127
log.error(f"Solr query failed: {e}\nPayload: {payload}")
128128
raise
129129

130-
data = response.json()
131-
raw_docs = (data.get('response') or {}).get('docs') or []
132-
reformat_raw_doc = []
133-
for doc in raw_docs:
134-
clean_doc = dict()
135-
clean_doc['id'] = doc[self.UNIQUE_KEY]
136-
clean_doc['fields'] = dict()
137-
for k, v in doc.items():
138-
if k != self.UNIQUE_KEY:
139-
if isinstance(v, list):
140-
if v:
141-
if isinstance(v[0], str):
142-
clean_doc['fields'][k] = [clean_text(text) for text in v]
143-
else:
144-
clean_doc['fields'][k] = v
145-
else:
146-
log.warning(f"The field {k} is empty, skipped.")
147-
else:
148-
clean_doc['fields'][k] = v
149-
reformat_raw_doc.append(Document(**clean_doc))
150-
return reformat_raw_doc
130+
hits = (response.json().get('response') or {}).get('docs') or []
131+
result = []
132+
for hit in hits:
133+
doc_id = hit.get(self.UNIQUE_KEY)
134+
fields = {
135+
key: self._normalize(value)
136+
for key, value in hit.items()
137+
if key != self.UNIQUE_KEY
138+
}
139+
140+
result.append(Document(id=doc_id, fields=fields))
141+
return result
142+
143+
@staticmethod
144+
def _normalize(value: Any) -> List[str]:
145+
"""Normalize a field value into a list of cleaned strings or throws an exception."""
146+
try:
147+
if value is None:
148+
return []
149+
150+
if isinstance(value, str):
151+
return [clean_text(value)]
152+
153+
if isinstance(value, list):
154+
return [clean_text(v) if isinstance(v, str) else str(v) for v in value]
155+
156+
if isinstance(value, dict):
157+
cleaned_dict = {
158+
k: clean_text(v) if isinstance(v, str) else v
159+
for k, v in value.items()
160+
}
161+
return [json.dumps(cleaned_dict)]
162+
163+
return [str(value)]
164+
except Exception as e:
165+
raise ValueError(f"Failed to normalize value: {value}") from e

rre-dataset-generator/tests/unit/test_elasticsearch_search_engine.py

Lines changed: 26 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -21,24 +21,29 @@ def elasticsearch_config():
2121
"""Fixture that loads a valid OpenSearch config for unit tests."""
2222
return Config.load("tests/unit/resources/elasticsearch_good_config.yaml")
2323

24-
def test_elasticsearch_search_engine(monkeypatch, elasticsearch_config):
25-
url = "https://fakeurl"
26-
search_engine = ElasticsearchSearchEngine(url)
27-
28-
payload = json.dumps({"match_all": {}})
29-
30-
mock_doc = {
24+
@pytest.fixture
25+
def mock_doc():
26+
return {
3127
"_id": "1",
3228
'_source': {
33-
"mock_title": "A first mocked title",
34-
"mock_description": "A first mocked description"
29+
"mock_title": ["A first mocked title"],
30+
"mock_description": ["A first mocked description"]
3531
}
3632
}
37-
mock_dict = {
33+
34+
@pytest.fixture
35+
def mock_dict(mock_doc):
36+
return {
3837
'id': mock_doc['_id'],
3938
'fields': mock_doc["_source"]
4039
}
4140

41+
def test_elasticsearch_search_engine_fetch_for_query_generation(monkeypatch, elasticsearch_config, mock_doc, mock_dict):
42+
url = "https://fakeurl"
43+
search_engine = ElasticsearchSearchEngine(url)
44+
45+
payload = json.dumps({"match_all": {}})
46+
4247
# apply the monkeypatch for requests.post to mock_post
4348
monkeypatch.setattr(requests, "post",
4449
lambda *args, **kwargs: MockResponseElasticsearchEngine([mock_doc], status_code=200)
@@ -48,6 +53,17 @@ def test_elasticsearch_search_engine(monkeypatch, elasticsearch_config):
4853
doc_number=elasticsearch_config.doc_number,
4954
doc_fields=elasticsearch_config.doc_fields)
5055
assert result[0] == Document(**mock_dict)
56+
57+
def test_elasticsearch_search_engine_fetch_for_evaluation(monkeypatch, elasticsearch_config, mock_doc, mock_dict):
58+
url = "https://fakeurl"
59+
search_engine = ElasticsearchSearchEngine(url)
60+
61+
payload = json.dumps({"match_all": {}})
62+
63+
# apply the monkeypatch for requests.post to mock_post
64+
monkeypatch.setattr(requests, "post",
65+
lambda *args, **kwargs: MockResponseElasticsearchEngine([mock_doc], status_code=200)
66+
)
5167
# search_engine.extract_documents_to_evaluate_system, which contains requests.post, uses the monkeypatch
5268
result = search_engine.fetch_for_evaluation(keyword="and",
5369
query_template=elasticsearch_config.query_template,

rre-dataset-generator/tests/unit/test_solr_search_engine.py

Lines changed: 26 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -19,22 +19,27 @@ def solr_config():
1919
"""Fixture that loads a valid OpenSearch config for unit tests."""
2020
return Config.load("tests/unit/resources/solr_good_config.yaml")
2121

22-
def test_solr_search_engine(monkeypatch, solr_config):
23-
monkeypatch.setattr(requests, "get", lambda *args, **kwargs: MockResponseUniqueKey(ident="mock_id"))
24-
search_engine = SolrSearchEngine("https://fakeurl")
25-
26-
assert search_engine.UNIQUE_KEY == "mock_id"
27-
28-
mock_doc = {
22+
@pytest.fixture
23+
def mock_doc():
24+
return {
2925
"mock_id": "1",
30-
"mock_title": "A first mocked title",
31-
"mock_description": "A first mocked description"
26+
"mock_title": ["A first mocked title"],
27+
"mock_description": ["A first mocked description"]
3228
}
33-
mock_dict = {
29+
30+
@pytest.fixture
31+
def mock_dict(mock_doc):
32+
return {
3433
'id': mock_doc['mock_id'],
35-
'fields': {k:v for k, v in mock_doc.items() if k !='mock_id'}
34+
'fields': {k: v for k, v in mock_doc.items() if k != 'mock_id'}
3635
}
3736

37+
def test_solr_search_engine_fetch_for_query_generation(monkeypatch, solr_config, mock_doc, mock_dict):
38+
monkeypatch.setattr(requests, "get", lambda *args, **kwargs: MockResponseUniqueKey(ident="mock_id"))
39+
search_engine = SolrSearchEngine("https://fakeurl")
40+
41+
assert search_engine.UNIQUE_KEY == "mock_id"
42+
3843
# apply the monkeypatch for requests.post to mock_post
3944
monkeypatch.setattr(requests, "post", lambda *args, **kwargs: MockResponseSolrEngine([mock_doc], status_code=200))
4045

@@ -43,6 +48,16 @@ def test_solr_search_engine(monkeypatch, solr_config):
4348
doc_number=solr_config.doc_number,
4449
doc_fields=solr_config.doc_fields)
4550
assert result[0] == Document(**mock_dict)
51+
52+
def test_solr_search_engine_fetch_for_evaluation(monkeypatch, solr_config, mock_doc, mock_dict):
53+
monkeypatch.setattr(requests, "get", lambda *args, **kwargs: MockResponseUniqueKey(ident="mock_id"))
54+
search_engine = SolrSearchEngine("https://fakeurl")
55+
56+
assert search_engine.UNIQUE_KEY == "mock_id"
57+
58+
# apply the monkeypatch for requests.post to mock_post
59+
monkeypatch.setattr(requests, "post", lambda *args, **kwargs: MockResponseSolrEngine([mock_doc], status_code=200))
60+
4661
# search_engine.extract_documents_to_evaluate_system, which contains requests.post, uses the monkeypatch
4762
result = search_engine.fetch_for_evaluation(keyword="and",
4863
query_template=solr_config.query_template,

0 commit comments

Comments
 (0)