forked from docarray/docarray
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocument.py
More file actions
187 lines (152 loc) · 6.46 KB
/
document.py
File metadata and controls
187 lines (152 loc) · 6.46 KB
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
from typing import Optional, overload, TYPE_CHECKING, Dict, Union
from docarray.array.base import BaseDocumentArray
from docarray.array.mixins import AllMixins
if TYPE_CHECKING:
from docarray.typing import DocumentArraySourceType
from docarray.array.memory import DocumentArrayInMemory
from docarray.array.sqlite import DocumentArraySqlite
from docarray.array.annlite import DocumentArrayAnnlite
from docarray.array.weaviate import DocumentArrayWeaviate
from docarray.array.elastic import DocumentArrayElastic
from docarray.array.redis import DocumentArrayRedis
from docarray.array.storage.sqlite import SqliteConfig
from docarray.array.storage.annlite import AnnliteConfig
from docarray.array.storage.weaviate import WeaviateConfig
from docarray.array.storage.elastic import ElasticConfig
from docarray.array.storage.redis import RedisConfig
class DocumentArray(AllMixins, BaseDocumentArray):
"""
DocumentArray is a list-like container of :class:`~docarray.Document` objects.
A DocumentArray can be used to store, embed, and retrieve :class:`~docarray.Document` objects.
.. code-block:: python
from docarray import Document, DocumentArray
da = DocumentArray(
[Document(text='The cake is a lie'), Document(text='Do a barrel roll!')]
)
da.apply(Document.embed_feature_hashing)
query = Document(text='Can i have some cake?').embed_feature_hashing()
query.match(da, metric='jaccard', use_scipy=True)
print(query.matches[:, ('text', 'scores__jaccard__value')])
.. code-block:: bash
[['The cake is a lie', 'Do a barrel roll!'], [0.9, 1.0]]
A DocumentArray can also :ref:`embed its contents using a neural network <embed-via-model>`,
process them using an :ref:`external Flow or Executor <da-post>`, and persist Documents in a :ref:`Document Store <doc-store>` for
fast vector search:
.. code-block:: python
from docarray import Document, DocumentArray
import numpy as np
n_dim = 3
metric = 'Euclidean'
# initialize a DocumentArray with ANNLiter Document Store
da = DocumentArray(
storage='annlite',
config={'n_dim': n_dim, 'columns': [('price', 'float')], 'metric': metric},
)
# add Documents to the DocumentArray
with da:
da.extend(
[
Document(id=f'r{i}', embedding=i * np.ones(n_dim), tags={'price': i})
for i in range(10)
]
)
# perform vector search
np_query = np.ones(n_dim) * 8
results = da.find(np_query)
.. seealso::
For further details, see our :ref:`user guide <documentarray>`.
"""
@overload
def __new__(
cls,
_docs: Optional['DocumentArraySourceType'] = None,
copy: bool = False,
subindex_configs: Optional[Dict[str, 'None']] = None,
) -> 'DocumentArrayInMemory':
"""Create an in-memory DocumentArray object."""
...
@overload
def __new__(
cls,
_docs: Optional['DocumentArraySourceType'] = None,
storage: str = 'sqlite',
config: Optional[Union['SqliteConfig', Dict]] = None,
subindex_configs: Optional[Dict[str, Dict]] = None,
) -> 'DocumentArraySqlite':
"""Create a SQLite-powered DocumentArray object."""
...
@overload
def __new__(
cls,
_docs: Optional['DocumentArraySourceType'] = None,
storage: str = 'weaviate',
config: Optional[Union['WeaviateConfig', Dict]] = None,
subindex_configs: Optional[Dict[str, Dict]] = None,
) -> 'DocumentArrayWeaviate':
"""Create a Weaviate-powered DocumentArray object."""
...
@overload
def __new__(
cls,
_docs: Optional['DocumentArraySourceType'] = None,
storage: str = 'annlite',
config: Optional[Union['AnnliteConfig', Dict]] = None,
subindex_configs: Optional[Dict[str, Dict]] = None,
) -> 'DocumentArrayAnnlite':
"""Create a AnnLite-powered DocumentArray object."""
...
@overload
def __new__(
cls,
_docs: Optional['DocumentArraySourceType'] = None,
storage: str = 'elasticsearch',
config: Optional[Union['ElasticConfig', Dict]] = None,
subindex_configs: Optional[Dict[str, Dict]] = None,
) -> 'DocumentArrayElastic':
"""Create a Elastic-powered DocumentArray object."""
...
@overload
def __new__(
cls,
_docs: Optional['DocumentArraySourceType'] = None,
storage: str = 'redis',
config: Optional[Union['RedisConfig', Dict]] = None,
) -> 'DocumentArrayRedis':
"""Create a Redis-powered DocumentArray object."""
...
def __enter__(self):
return self
def __exit__(self, *args, **kwargs):
"""
Ensures that offset2ids are stored in the db after
operations in the DocumentArray are performed.
"""
self._save_offset2ids()
def __new__(cls, *args, storage: str = 'memory', **kwargs):
if cls is DocumentArray:
if storage == 'memory':
from docarray.array.memory import DocumentArrayInMemory
instance = super().__new__(DocumentArrayInMemory)
elif storage == 'sqlite':
from docarray.array.sqlite import DocumentArraySqlite
instance = super().__new__(DocumentArraySqlite)
elif storage == 'annlite':
from docarray.array.annlite import DocumentArrayAnnlite
instance = super().__new__(DocumentArrayAnnlite)
elif storage == 'weaviate':
from docarray.array.weaviate import DocumentArrayWeaviate
instance = super().__new__(DocumentArrayWeaviate)
elif storage == 'qdrant':
from docarray.array.qdrant import DocumentArrayQdrant
instance = super().__new__(DocumentArrayQdrant)
elif storage == 'elasticsearch':
from docarray.array.elastic import DocumentArrayElastic
instance = super().__new__(DocumentArrayElastic)
elif storage == 'redis':
from .redis import DocumentArrayRedis
instance = super().__new__(DocumentArrayRedis)
else:
raise ValueError(f'storage=`{storage}` is not supported.')
else:
instance = super().__new__(cls)
return instance