-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
search_engine.py
1656 lines (1446 loc) · 79.3 KB
/
search_engine.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# pylint: disable=too-many-public-methods
from copy import deepcopy
from typing import List, Optional, Union, Dict, Any, Generator
from abc import abstractmethod
import json
import logging
import time
from string import Template
import numpy as np
from tqdm import tqdm
from pydantic.error_wrappers import ValidationError
from haystack.document_stores import KeywordDocumentStore
from haystack.schema import Document, FilterType, Label
from haystack.utils.batching import get_batches_from_generator
from haystack.document_stores.filter_utils import LogicalFilterClause
from haystack.errors import DocumentStoreError, HaystackError
from haystack.nodes.retriever import DenseRetriever
from haystack.utils.scipy_utils import expit
logger = logging.getLogger(__name__)
def prepare_hosts(host, port):
"""
Create a list of host(s) + port(s) to allow direct client connections to multiple nodes,
in the format expected by the client.
"""
if isinstance(host, list):
if isinstance(port, list):
if not len(port) == len(host):
raise ValueError("Length of list `host` must match length of list `port`")
hosts = [{"host": h, "port": p} for h, p in zip(host, port)]
else:
hosts = [{"host": h, "port": port} for h in host]
else:
hosts = [{"host": host, "port": port}]
return hosts
class SearchEngineDocumentStore(KeywordDocumentStore):
"""
Base class implementing the common logic for Elasticsearch and Opensearch
"""
def __init__(
self,
client: Any,
index: str = "document",
label_index: str = "label",
search_fields: Union[str, list] = "content",
content_field: str = "content",
name_field: str = "name",
embedding_field: str = "embedding",
embedding_dim: int = 768,
custom_mapping: Optional[dict] = None,
excluded_meta_data: Optional[list] = None,
analyzer: str = "standard",
recreate_index: bool = False,
create_index: bool = True,
refresh_type: str = "wait_for",
similarity: str = "dot_product",
return_embedding: bool = False,
duplicate_documents: str = "overwrite",
scroll: str = "1d",
skip_missing_embeddings: bool = True,
synonyms: Optional[List] = None,
synonym_type: str = "synonym",
batch_size: int = 10_000,
):
super().__init__()
self.client = client
self._RequestError: Any = Exception
# configure mappings to ES fields that will be used for querying / displaying results
if type(search_fields) == str:
search_fields = [search_fields]
self.search_fields = search_fields
self.content_field = content_field
self.name_field = name_field
self.embedding_field = embedding_field
self.embedding_dim = embedding_dim
self.excluded_meta_data = excluded_meta_data
self.analyzer = analyzer
self.return_embedding = return_embedding
self.custom_mapping = custom_mapping
self.synonyms = synonyms
self.synonym_type = synonym_type
self.index: str = index
self.label_index: str = label_index
self.scroll = scroll
self.skip_missing_embeddings: bool = skip_missing_embeddings
self.duplicate_documents = duplicate_documents
self.refresh_type = refresh_type
self.batch_size = batch_size
if similarity in ["cosine", "dot_product", "l2"]:
self.similarity: str = similarity
else:
raise DocumentStoreError(
f"Invalid value {similarity} for similarity, choose between 'cosine', 'l2' and 'dot_product'"
)
client_info = self.client.info()
self.server_version = tuple(int(num) for num in client_info["version"]["number"].split("."))
self._init_indices(
index=index, label_index=label_index, create_index=create_index, recreate_index=recreate_index
)
def _init_indices(self, index: str, label_index: str, create_index: bool, recreate_index: bool) -> None:
if recreate_index:
self._index_delete(index)
self._index_delete(label_index)
if not self._index_exists(index) and (create_index or recreate_index):
self._create_document_index(index)
if self.custom_mapping:
logger.warning("Cannot validate index for custom mappings. Skipping index validation.")
else:
self._validate_and_adjust_document_index(index)
if not self._index_exists(label_index) and (create_index or recreate_index):
self._create_label_index(label_index)
def _split_document_list(
self, documents: Union[List[dict], List[Document]], number_of_lists: int
) -> Generator[Union[List[dict], List[Document]], None, None]:
chunk_size = max((len(documents) + 1) // number_of_lists, 1)
for i in range(0, len(documents), chunk_size):
yield documents[i : i + chunk_size]
@abstractmethod
def _do_bulk(self, *args, **kwargs):
pass
@abstractmethod
def _do_scan(self, *args, **kwargs):
pass
@abstractmethod
def query_by_embedding(
self,
query_emb: np.ndarray,
filters: Optional[FilterType] = None,
top_k: int = 10,
index: Optional[str] = None,
return_embedding: Optional[bool] = None,
headers: Optional[Dict[str, str]] = None,
scale_score: bool = True,
) -> List[Document]:
pass
@abstractmethod
def _create_document_index(self, index_name: str, headers: Optional[Dict[str, str]] = None):
pass
@abstractmethod
def _create_label_index(self, index_name: str, headers: Optional[Dict[str, str]] = None):
pass
@abstractmethod
def _validate_and_adjust_document_index(self, index_name: str, headers: Optional[Dict[str, str]] = None):
pass
@abstractmethod
def _get_vector_similarity_query(self, query_emb: np.ndarray, top_k: int):
pass
@abstractmethod
def _get_raw_similarity_score(self, score):
pass
def _bulk(
self,
documents: Union[List[dict], List[Document]],
headers: Optional[Dict[str, str]] = None,
refresh: str = "wait_for",
_timeout: int = 1,
_remaining_tries: int = 10,
) -> None:
"""
Bulk index documents using a custom retry logic with
exponential backoff and exponential batch size reduction to avoid overloading the cluster.
The ingest node returns '429 Too Many Requests' when the write requests can't be
processed because there are too many requests in the queue or the single request is too large and exceeds the
memory of the nodes. Since the error code is the same for both of these cases we need to wait
and reduce the batch size simultaneously.
:param documents: List of documents to index
:param headers: Optional headers to pass to the bulk request
:param refresh: Refresh policy for the bulk request
:param _timeout: Timeout for the exponential backoff
:param _remaining_tries: Number of remaining retries
"""
try:
self._do_bulk(self.client, documents, refresh=self.refresh_type, headers=headers)
except Exception as e:
if hasattr(e, "status_code") and e.status_code == 429: # type: ignore
logger.warning(
"Failed to insert a batch of '%s' documents because of a 'Too Many Requests' response. "
"Splitting the number of documents into two chunks with the same size and retrying in %s seconds.",
len(documents),
_timeout,
)
if len(documents) == 1:
logger.warning(
"Failed to index a single document. Your indexing queue on the cluster is probably full. Try resizing your cluster or reducing the number of parallel processes that are writing to the cluster."
)
time.sleep(_timeout)
_remaining_tries -= 1
if _remaining_tries == 0:
raise DocumentStoreError("Last try of bulk indexing documents failed.")
for split_docs in self._split_document_list(documents, 2):
self._bulk(
documents=split_docs,
headers=headers,
refresh=refresh,
_timeout=_timeout * 2,
_remaining_tries=_remaining_tries,
)
return
raise e
# TODO: Add flexibility to define other non-meta and meta fields expected by the Document class
def _create_document_field_map(self) -> Dict:
return {self.content_field: "content", self.embedding_field: "embedding"}
def get_document_by_id(
self, id: str, index: Optional[str] = None, headers: Optional[Dict[str, str]] = None
) -> Optional[Document]:
"""Fetch a document by specifying its text id string"""
index = index or self.index
documents = self.get_documents_by_id([id], index=index, headers=headers)
if documents:
return documents[0]
else:
return None
def get_documents_by_id(
self,
ids: List[str],
index: Optional[str] = None,
batch_size: int = 10_000,
headers: Optional[Dict[str, str]] = None,
) -> List[Document]:
"""
Fetch documents by specifying a list of text id strings.
:param ids: List of document IDs. Be aware that passing a large number of ids might lead to performance issues.
:param index: search index where the documents are stored. If not supplied,
self.index will be used.
:param batch_size: Maximum number of results for each query.
Limited to 10,000 documents by default.
To reduce the pressure on the cluster, you can lower this limit, at the expense
of longer retrieval times.
:param headers: Custom HTTP headers to pass to the client (e.g. {'Authorization': 'Basic YWRtaW46cm9vdA=='})
Check out https://www.elastic.co/guide/en/elasticsearch/reference/current/http-clients.html for more information.
"""
index = index or self.index
documents = []
for i in range(0, len(ids), batch_size):
ids_for_batch = ids[i : i + batch_size]
query = {"size": len(ids_for_batch), "query": {"ids": {"values": ids_for_batch}}}
if not self.return_embedding and self.embedding_field:
query["_source"] = {"excludes": [self.embedding_field]}
result = self._search(index=index, **query, headers=headers)["hits"]["hits"]
documents.extend([self._convert_es_hit_to_document(hit) for hit in result])
return documents
def get_metadata_values_by_key(
self,
key: str,
query: Optional[str] = None,
filters: Optional[FilterType] = None,
index: Optional[str] = None,
headers: Optional[Dict[str, str]] = None,
) -> List[dict]:
"""
Get values associated with a metadata key. The output is in the format:
[{"value": "my-value-1", "count": 23}, {"value": "my-value-2", "count": 12}, ... ]
:param key: the meta key name to get the values for.
:param query: narrow down the scope to documents matching the query string.
:param filters: Narrow down the scope to documents that match the given filters.
Filters are defined as nested dictionaries. The keys of the dictionaries can be a logical
operator (`"$and"`, `"$or"`, `"$not"`), a comparison operator (`"$eq"`, `"$in"`, `"$gt"`,
`"$gte"`, `"$lt"`, `"$lte"`) or a metadata field name.
Logical operator keys take a dictionary of metadata field names and/or logical operators as
value. Metadata field names take a dictionary of comparison operators as value. Comparison
operator keys take a single value or (in case of `"$in"`) a list of values as value.
If no logical operator is provided, `"$and"` is used as default operation. If no comparison
operator is provided, `"$eq"` (or `"$in"` if the comparison value is a list) is used as default
operation.
__Example__:
```python
filters = {
"$and": {
"type": {"$eq": "article"},
"date": {"$gte": "2015-01-01", "$lt": "2021-01-01"},
"rating": {"$gte": 3},
"$or": {
"genre": {"$in": ["economy", "politics"]},
"publisher": {"$eq": "nytimes"}
}
}
}
```
:param index: search index where the meta values should be searched. If not supplied,
self.index will be used.
:param headers: Custom HTTP headers to pass to the client (e.g. {'Authorization': 'Basic YWRtaW46cm9vdA=='})
Check out https://www.elastic.co/guide/en/elasticsearch/reference/current/http-clients.html for more information.
"""
body: dict = {
"size": 0,
"aggs": {"metadata_agg": {"composite": {"sources": [{key: {"terms": {"field": key}}}]}}},
}
if query:
body["query"] = {
"bool": {
"should": [{"multi_match": {"query": query, "type": "most_fields", "fields": self.search_fields}}]
}
}
if filters:
if not body.get("query"):
body["query"] = {"bool": {}}
body["query"]["bool"].update({"filter": LogicalFilterClause.parse(filters).convert_to_elasticsearch()})
result = self._search(**body, index=index, headers=headers)
values = []
current_buckets = result["aggregations"]["metadata_agg"]["buckets"]
after_key = result["aggregations"]["metadata_agg"].get("after_key", False)
for bucket in current_buckets:
values.append({"value": bucket["key"][key], "count": bucket["doc_count"]})
# Only 10 results get returned at a time, so apply pagination
while after_key:
body["aggs"]["metadata_agg"]["composite"]["after"] = after_key
result = self._search(**body, index=index, headers=headers)
current_buckets = result["aggregations"]["metadata_agg"]["buckets"]
after_key = result["aggregations"]["metadata_agg"].get("after_key", False)
for bucket in current_buckets:
values.append({"value": bucket["key"][key], "count": bucket["doc_count"]})
return values
def write_documents(
self,
documents: Union[List[dict], List[Document]],
index: Optional[str] = None,
batch_size: Optional[int] = None,
duplicate_documents: Optional[str] = None,
headers: Optional[Dict[str, str]] = None,
):
"""
Indexes documents for later queries.
If a document with the same ID already exists:
a) (Default) Manage duplication according to the `duplicate_documents` parameter.
b) If `self.update_existing_documents=True` for DocumentStore: Overwrite existing documents.
(This is only relevant if you pass your own ID when initializing a `Document`.
If you don't set custom IDs for your Documents or just pass a list of dictionaries here,
they automatically get UUIDs assigned. See the `Document` class for details.)
:param documents: A list of Python dictionaries or a list of Haystack Document objects.
For documents as dictionaries, the format is {"content": "<the-actual-text>"}.
Optionally: Include meta data via {"content": "<the-actual-text>",
"meta":{"name": "<some-document-name>, "author": "somebody", ...}}
You can use it for filtering and you can access it in the responses of the Finder.
Advanced: If you are using your own field mapping, change the key names in the dictionary
to what you have set for self.content_field and self.name_field.
:param index: search index where the documents should be indexed. If you don't specify it, self.index is used.
:param batch_size: Number of documents that are passed to the bulk function at each round.
If not specified, self.batch_size is used.
:param duplicate_documents: Handle duplicate documents based on parameter options.
Parameter options: ( 'skip','overwrite','fail')
skip: Ignore the duplicate documents
overwrite: Update any existing documents with the same ID when adding documents.
fail: Raises an error if the document ID of the document being added already
exists.
:param headers: Custom HTTP headers to pass to the client (for example {'Authorization': 'Basic YWRtaW46cm9vdA=='})
For more information, see [HTTP/REST clients and security](https://www.elastic.co/guide/en/elasticsearch/reference/current/http-clients.html).
:raises DuplicateDocumentError: Exception trigger on duplicate document
:return: None
"""
if index and not self._index_exists(index, headers=headers):
self._create_document_index(index, headers=headers)
if index is None:
index = self.index
batch_size = batch_size or self.batch_size
duplicate_documents = duplicate_documents or self.duplicate_documents
assert (
duplicate_documents in self.duplicate_documents_options
), f"duplicate_documents parameter must be {', '.join(self.duplicate_documents_options)}"
field_map = self._create_document_field_map()
document_objects = [Document.from_dict(d, field_map=field_map) if isinstance(d, dict) else d for d in documents]
document_objects = self._handle_duplicate_documents(
documents=document_objects, index=index, duplicate_documents=duplicate_documents, headers=headers
)
documents_to_index = []
for doc in document_objects:
index_message: Dict[str, Any] = {
"_op_type": "index" if duplicate_documents == "overwrite" else "create",
"_index": index,
"_id": str(doc.id),
# use _source explicitly to avoid conflicts with automatic field detection by ES/OS clients (e.g. "version")
"_source": self._get_source(doc, field_map),
}
documents_to_index.append(index_message)
# Pass batch_size number of documents to bulk
if len(documents_to_index) % batch_size == 0:
self._bulk(documents_to_index, refresh=self.refresh_type, headers=headers)
documents_to_index = []
if documents_to_index:
self._bulk(documents_to_index, refresh=self.refresh_type, headers=headers)
def _get_source(self, doc: Document, field_map: Dict[str, Any]) -> Dict[str, Any]:
"""Convert a Document object to a dictionary that can be used as the "_source" field in an ES/OS index message."""
_source: Dict[str, Any] = doc.to_dict(field_map=field_map)
# cast embedding type as ES/OS cannot deal with np.array
if isinstance(_source.get(self.embedding_field), np.ndarray):
_source[self.embedding_field] = _source[self.embedding_field].tolist()
# we already have the id in the index message
_source.pop("id", None)
# don't index query score and empty fields
_source.pop("score", None)
_source = {k: v for k, v in _source.items() if v is not None}
# In order to have a flat structure in ES/OS + similar behavior to the other DocumentStores,
# we "unnest" all value within "meta"
_source.update(_source.pop("meta", None) or {})
return _source
def write_labels(
self,
labels: Union[List[Label], List[dict]],
index: Optional[str] = None,
headers: Optional[Dict[str, str]] = None,
batch_size: int = 10_000,
):
"""Write annotation labels into document store.
:param labels: A list of Python dictionaries or a list of Haystack Label objects.
:param index: search index where the labels should be stored. If not supplied, self.label_index will be used.
:param batch_size: Number of labels that are passed to the bulk function at each round.
:param headers: Custom HTTP headers to pass to the client (e.g. {'Authorization': 'Basic YWRtaW46cm9vdA=='})
Check out https://www.elastic.co/guide/en/elasticsearch/reference/current/http-clients.html for more information.
"""
index = index or self.label_index
if index and not self._index_exists(index, headers=headers):
self._create_label_index(index, headers=headers)
label_list: List[Label] = [Label.from_dict(label) if isinstance(label, dict) else label for label in labels]
duplicate_ids: list = [label.id for label in self._get_duplicate_labels(label_list, index=index)]
if len(duplicate_ids) > 0:
logger.warning(
"Duplicate Label IDs: Inserting a Label whose id already exists in this document store."
" This will overwrite the old Label. Please make sure Label.id is a unique identifier of"
" the answer annotation and not the question."
" Problematic ids: %s",
",".join(duplicate_ids),
)
labels_to_index = []
for label in label_list:
# create timestamps if not available yet
if not label.created_at:
label.created_at = time.strftime("%Y-%m-%d %H:%M:%S")
if not label.updated_at:
label.updated_at = label.created_at
index_message: Dict[str, Any] = {
"_op_type": "index"
if self.duplicate_documents == "overwrite" or label.id in duplicate_ids
else "create",
"_index": index,
}
_source = label.to_dict()
# set id for elastic
if _source.get("id") is not None:
index_message["_id"] = str(_source.pop("id"))
# use _source explicitly to avoid conflicts with automatic field detection by ES/OS clients (e.g. "version")
index_message["_source"] = _source
labels_to_index.append(index_message)
# Pass batch_size number of labels to bulk
if len(labels_to_index) % batch_size == 0:
self._bulk(labels_to_index, refresh=self.refresh_type, headers=headers)
labels_to_index = []
if labels_to_index:
self._bulk(labels_to_index, refresh=self.refresh_type, headers=headers)
def update_document_meta(
self, id: str, meta: Dict[str, str], index: Optional[str] = None, headers: Optional[Dict[str, str]] = None
):
"""
Update the metadata dictionary of a document by specifying its string id
"""
if not index:
index = self.index
body = {"doc": meta}
self._update(index=index, id=id, **body, refresh=self.refresh_type, headers=headers)
def get_document_count(
self,
filters: Optional[FilterType] = None,
index: Optional[str] = None,
only_documents_without_embedding: bool = False,
headers: Optional[Dict[str, str]] = None,
) -> int:
"""
Return the number of documents in the document store.
"""
index = index or self.index
body: dict = {"query": {"bool": {}}}
if only_documents_without_embedding:
body["query"]["bool"]["must_not"] = [{"exists": {"field": self.embedding_field}}]
if filters:
body["query"]["bool"]["filter"] = LogicalFilterClause.parse(filters).convert_to_elasticsearch()
result = self._count(index=index, body=body, headers=headers)
count = result["count"]
return count
def get_label_count(self, index: Optional[str] = None, headers: Optional[Dict[str, str]] = None) -> int:
"""
Return the number of labels in the document store
"""
index = index or self.label_index
return self.get_document_count(index=index, headers=headers)
def get_embedding_count(
self,
index: Optional[str] = None,
filters: Optional[FilterType] = None,
headers: Optional[Dict[str, str]] = None,
) -> int:
"""
Return the count of embeddings in the document store.
"""
index = index or self.index
body: dict = {"query": {"bool": {"must": [{"exists": {"field": self.embedding_field}}]}}}
if filters:
body["query"]["bool"]["filter"] = LogicalFilterClause.parse(filters).convert_to_elasticsearch()
result = self._count(index=index, body=body, headers=headers)
count = result["count"]
return count
def get_all_documents(
self,
index: Optional[str] = None,
filters: Optional[FilterType] = None,
return_embedding: Optional[bool] = None,
batch_size: int = 10_000,
headers: Optional[Dict[str, str]] = None,
) -> List[Document]:
"""
Get documents from the document store.
:param index: Name of the index to get the documents from. If None, the
DocumentStore's default index (self.index) will be used.
:param filters: Optional filters to narrow down the documents to return.
Filters are defined as nested dictionaries. The keys of the dictionaries can be a logical
operator (`"$and"`, `"$or"`, `"$not"`), a comparison operator (`"$eq"`, `"$in"`, `"$gt"`,
`"$gte"`, `"$lt"`, `"$lte"`) or a metadata field name.
Logical operator keys take a dictionary of metadata field names and/or logical operators as
value. Metadata field names take a dictionary of comparison operators as value. Comparison
operator keys take a single value or (in case of `"$in"`) a list of values as value.
If no logical operator is provided, `"$and"` is used as default operation. If no comparison
operator is provided, `"$eq"` (or `"$in"` if the comparison value is a list) is used as default
operation.
__Example__:
```python
filters = {
"$and": {
"type": {"$eq": "article"},
"date": {"$gte": "2015-01-01", "$lt": "2021-01-01"},
"rating": {"$gte": 3},
"$or": {
"genre": {"$in": ["economy", "politics"]},
"publisher": {"$eq": "nytimes"}
}
}
}
```
:param return_embedding: Whether to return the document embeddings.
:param batch_size: When working with large number of documents, batching can help reduce memory footprint.
:param headers: Custom HTTP headers to pass to the client (e.g. {'Authorization': 'Basic YWRtaW46cm9vdA=='})
Check out https://www.elastic.co/guide/en/elasticsearch/reference/current/http-clients.html for more information.
"""
result = self.get_all_documents_generator(
index=index, filters=filters, return_embedding=return_embedding, batch_size=batch_size, headers=headers
)
documents = list(result)
return documents
def get_all_documents_generator(
self,
index: Optional[str] = None,
filters: Optional[FilterType] = None,
return_embedding: Optional[bool] = None,
batch_size: int = 10_000,
headers: Optional[Dict[str, str]] = None,
) -> Generator[Document, None, None]:
"""
Get documents from the document store. Under-the-hood, documents are fetched in batches from the
document store and yielded as individual documents. This method can be used to iteratively process
a large number of documents without having to load all documents in memory.
:param index: Name of the index to get the documents from. If None, the
DocumentStore's default index (self.index) will be used.
:param filters: Optional filters to narrow down the documents to return.
Filters are defined as nested dictionaries. The keys of the dictionaries can be a logical
operator (`"$and"`, `"$or"`, `"$not"`), a comparison operator (`"$eq"`, `"$in"`, `"$gt"`,
`"$gte"`, `"$lt"`, `"$lte"`) or a metadata field name.
Logical operator keys take a dictionary of metadata field names and/or logical operators as
value. Metadata field names take a dictionary of comparison operators as value. Comparison
operator keys take a single value or (in case of `"$in"`) a list of values as value.
If no logical operator is provided, `"$and"` is used as default operation. If no comparison
operator is provided, `"$eq"` (or `"$in"` if the comparison value is a list) is used as default
operation.
__Example__:
```python
filters = {
"$and": {
"type": {"$eq": "article"},
"date": {"$gte": "2015-01-01", "$lt": "2021-01-01"},
"rating": {"$gte": 3},
"$or": {
"genre": {"$in": ["economy", "politics"]},
"publisher": {"$eq": "nytimes"}
}
}
}
```
:param return_embedding: Whether to return the document embeddings.
:param batch_size: When working with large number of documents, batching can help reduce memory footprint.
:param headers: Custom HTTP headers to pass to the client (e.g. {'Authorization': 'Basic YWRtaW46cm9vdA=='})
Check out https://www.elastic.co/guide/en/elasticsearch/reference/current/http-clients.html for more information.
"""
if index is None:
index = self.index
if return_embedding is None:
return_embedding = self.return_embedding
excludes = None
if not return_embedding and self.embedding_field:
excludes = [self.embedding_field]
result = self._get_all_documents_in_index(
index=index, filters=filters, batch_size=batch_size, headers=headers, excludes=excludes
)
for hit in result:
document = self._convert_es_hit_to_document(hit)
yield document
def get_all_labels(
self,
index: Optional[str] = None,
filters: Optional[FilterType] = None,
headers: Optional[Dict[str, str]] = None,
batch_size: int = 10_000,
) -> List[Label]:
"""
Return all labels in the document store
"""
index = index or self.label_index
result = list(
self._get_all_documents_in_index(index=index, filters=filters, batch_size=batch_size, headers=headers)
)
try:
labels = [Label.from_dict({**hit["_source"], "id": hit["_id"]}) for hit in result]
except ValidationError as e:
raise DocumentStoreError(
f"Failed to create labels from the content of index '{index}'. Are you sure this index contains labels?"
) from e
return labels
def _get_all_documents_in_index(
self,
index: str,
filters: Optional[FilterType] = None,
batch_size: int = 10_000,
only_documents_without_embedding: bool = False,
headers: Optional[Dict[str, str]] = None,
excludes: Optional[List[str]] = None,
) -> Generator[dict, None, None]:
"""
Return all documents in a specific index in the document store
"""
body: dict = {"query": {"bool": {}}}
if filters:
body["query"]["bool"]["filter"] = LogicalFilterClause.parse(filters).convert_to_elasticsearch()
if only_documents_without_embedding:
body["query"]["bool"]["must_not"] = [{"exists": {"field": self.embedding_field}}]
if excludes:
body["_source"] = {"excludes": excludes}
result = self._do_scan(
self.client, query=body, index=index, size=batch_size, scroll=self.scroll, headers=headers
)
yield from result
def query(
self,
query: Optional[str],
filters: Optional[FilterType] = None,
top_k: int = 10,
custom_query: Optional[str] = None,
index: Optional[str] = None,
headers: Optional[Dict[str, str]] = None,
all_terms_must_match: bool = False,
scale_score: bool = True,
) -> List[Document]:
"""
Scan through documents in DocumentStore and return a small number documents
that are most relevant to the query as defined by the BM25 algorithm.
:param query: The query
:param filters: Optional filters to narrow down the search space to documents whose metadata fulfill certain
conditions.
Filters are defined as nested dictionaries. The keys of the dictionaries can be a logical
operator (`"$and"`, `"$or"`, `"$not"`), a comparison operator (`"$eq"`, `"$in"`, `"$gt"`,
`"$gte"`, `"$lt"`, `"$lte"`) or a metadata field name.
Logical operator keys take a dictionary of metadata field names and/or logical operators as
value. Metadata field names take a dictionary of comparison operators as value. Comparison
operator keys take a single value or (in case of `"$in"`) a list of values as value.
If no logical operator is provided, `"$and"` is used as default operation. If no comparison
operator is provided, `"$eq"` (or `"$in"` if the comparison value is a list) is used as default
operation.
__Example__:
```python
filters = {
"$and": {
"type": {"$eq": "article"},
"date": {"$gte": "2015-01-01", "$lt": "2021-01-01"},
"rating": {"$gte": 3},
"$or": {
"genre": {"$in": ["economy", "politics"]},
"publisher": {"$eq": "nytimes"}
}
}
}
# or simpler using default operators
filters = {
"type": "article",
"date": {"$gte": "2015-01-01", "$lt": "2021-01-01"},
"rating": {"$gte": 3},
"$or": {
"genre": ["economy", "politics"],
"publisher": "nytimes"
}
}
```
To use the same logical operator multiple times on the same level, logical operators take
optionally a list of dictionaries as value.
__Example__:
```python
filters = {
"$or": [
{
"$and": {
"Type": "News Paper",
"Date": {
"$lt": "2019-01-01"
}
}
},
{
"$and": {
"Type": "Blog Post",
"Date": {
"$gte": "2019-01-01"
}
}
}
]
}
```
:param top_k: How many documents to return per query.
:param custom_query: query string containing a mandatory `${query}` and an optional `${filters}` placeholder.
::
**An example custom_query:**
```python
{
"size": 10,
"query": {
"bool": {
"should": [{"multi_match": {
"query": ${query}, // mandatory query placeholder
"type": "most_fields",
"fields": ["content", "title"]}}],
"filter": ${filters} // optional filters placeholder
}
},
}
```
**For this custom_query, a sample retrieve() could be:**
```python
self.retrieve(query="Why did the revenue increase?",
filters={"years": ["2019"], "quarters": ["Q1", "Q2"]})
```
Optionally, highlighting can be defined by specifying the highlight settings.
See https://www.elastic.co/guide/en/elasticsearch/reference/current/highlighting.html.
You will find the highlighted output in the returned Document's meta field by key "highlighted".
::
**Example custom_query with highlighting:**
```python
{
"size": 10,
"query": {
"bool": {
"should": [{"multi_match": {
"query": ${query}, // mandatory query placeholder
"type": "most_fields",
"fields": ["content", "title"]}}],
}
},
"highlight": { // enable highlighting
"fields": { // for fields content and title
"content": {},
"title": {}
}
},
}
```
**For this custom_query, highlighting info can be accessed by:**
```python
docs = self.retrieve(query="Why did the revenue increase?")
highlighted_content = docs[0].meta["highlighted"]["content"]
highlighted_title = docs[0].meta["highlighted"]["title"]
```
:param index: The name of the index in the DocumentStore from which to retrieve documents
:param headers: Custom HTTP headers to pass to the client (e.g. {'Authorization': 'Basic YWRtaW46cm9vdA=='})
Check out https://www.elastic.co/guide/en/elasticsearch/reference/current/http-clients.html for more information.
:param all_terms_must_match: Whether all terms of the query must match the document.
If true all query terms must be present in a document in order to be retrieved (i.e the AND operator is being used implicitly between query terms: "cozy fish restaurant" -> "cozy AND fish AND restaurant").
Otherwise at least one query term must be present in a document in order to be retrieved (i.e the OR operator is being used implicitly between query terms: "cozy fish restaurant" -> "cozy OR fish OR restaurant").
Defaults to false.
:param scale_score: Whether to scale the similarity score to the unit interval (range of [0,1]).
If true (default) similarity scores (e.g. cosine or dot_product) which naturally have a different value range will be scaled to a range of [0,1], where 1 means extremely relevant.
Otherwise raw similarity scores (e.g. cosine or dot_product) will be used.
"""
if index is None:
index = self.index
body = self._construct_query_body(
query=query,
filters=filters,
top_k=top_k,
custom_query=custom_query,
all_terms_must_match=all_terms_must_match,
)
result = self._search(index=index, **body, headers=headers)["hits"]["hits"]
documents = [self._convert_es_hit_to_document(hit, scale_score=scale_score) for hit in result]
return documents
def query_batch(
self,
queries: List[str],
filters: Optional[Union[FilterType, List[Optional[FilterType]]]] = None,
top_k: int = 10,
custom_query: Optional[str] = None,
index: Optional[str] = None,
headers: Optional[Dict[str, str]] = None,
all_terms_must_match: bool = False,
scale_score: bool = True,
batch_size: Optional[int] = None,
) -> List[List[Document]]:
"""
Scan through documents in DocumentStore and return a small number of documents
that are most relevant to the provided queries as defined by keyword matching algorithms like BM25.
This method lets you find relevant documents for list of query strings (output: List of Lists of Documents).
:param queries: List of query strings.
:param filters: Optional filters to narrow down the search space to documents whose metadata fulfill certain
conditions. Can be a single filter that will be applied to each query or a list of filters
(one filter per query).
Filters are defined as nested dictionaries. The keys of the dictionaries can be a logical
operator (`"$and"`, `"$or"`, `"$not"`), a comparison operator (`"$eq"`, `"$in"`, `"$gt"`,
`"$gte"`, `"$lt"`, `"$lte"`) or a metadata field name.
Logical operator keys take a dictionary of metadata field names and/or logical operators as
value. Metadata field names take a dictionary of comparison operators as value. Comparison
operator keys take a single value or (in case of `"$in"`) a list of values as value.
If no logical operator is provided, `"$and"` is used as default operation. If no comparison
operator is provided, `"$eq"` (or `"$in"` if the comparison value is a list) is used as default
operation.
__Example__:
```python
filters = {
"$and": {
"type": {"$eq": "article"},
"date": {"$gte": "2015-01-01", "$lt": "2021-01-01"},
"rating": {"$gte": 3},
"$or": {
"genre": {"$in": ["economy", "politics"]},
"publisher": {"$eq": "nytimes"}
}
}
}
# or simpler using default operators
filters = {
"type": "article",
"date": {"$gte": "2015-01-01", "$lt": "2021-01-01"},
"rating": {"$gte": 3},
"$or": {
"genre": ["economy", "politics"],
"publisher": "nytimes"
}
}
```
To use the same logical operator multiple times on the same level, logical operators take
optionally a list of dictionaries as value.
__Example__:
```python
filters = {
"$or": [
{
"$and": {
"Type": "News Paper",
"Date": {
"$lt": "2019-01-01"
}
}
},
{
"$and": {
"Type": "Blog Post",
"Date": {
"$gte": "2019-01-01"
}
}
}
]
}
```