faiss-haystack 1.0.0__tar.gz → 2.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (21) hide show
  1. faiss_haystack-2.1.0/CHANGELOG.md +25 -0
  2. faiss_haystack-2.1.0/LICENSE.txt +201 -0
  3. {faiss_haystack-1.0.0 → faiss_haystack-2.1.0}/PKG-INFO +15 -15
  4. faiss_haystack-2.1.0/README.md +13 -0
  5. {faiss_haystack-1.0.0 → faiss_haystack-2.1.0}/pyproject.toml +29 -8
  6. {faiss_haystack-1.0.0 → faiss_haystack-2.1.0}/src/haystack_integrations/components/retrievers/faiss/embedding_retriever.py +6 -3
  7. {faiss_haystack-1.0.0 → faiss_haystack-2.1.0}/src/haystack_integrations/document_stores/faiss/document_store.py +55 -28
  8. {faiss_haystack-1.0.0 → faiss_haystack-2.1.0}/tests/test_document_store.py +63 -48
  9. {faiss_haystack-1.0.0 → faiss_haystack-2.1.0}/tests/test_embedding_retriever.py +6 -4
  10. faiss_haystack-1.0.0/README.md +0 -17
  11. faiss_haystack-1.0.0/src/haystack_integrations/components/__init__.py +0 -3
  12. faiss_haystack-1.0.0/src/haystack_integrations/components/retrievers/__init__.py +0 -3
  13. faiss_haystack-1.0.0/src/haystack_integrations/document_stores/__init__.py +0 -0
  14. faiss_haystack-1.0.0/tests/__init__.py +0 -0
  15. {faiss_haystack-1.0.0 → faiss_haystack-2.1.0}/.gitignore +0 -0
  16. {faiss_haystack-1.0.0 → faiss_haystack-2.1.0}/pydoc/config_docusaurus.yml +0 -0
  17. {faiss_haystack-1.0.0 → faiss_haystack-2.1.0}/src/haystack_integrations/components/retrievers/faiss/__init__.py +0 -0
  18. {faiss_haystack-1.0.0/src/haystack_integrations/components/retrievers/faiss → faiss_haystack-2.1.0/src/haystack_integrations/components/retrievers}/py.typed +0 -0
  19. {faiss_haystack-1.0.0 → faiss_haystack-2.1.0}/src/haystack_integrations/document_stores/faiss/__init__.py +0 -0
  20. {faiss_haystack-1.0.0/src/haystack_integrations/document_stores/faiss → faiss_haystack-2.1.0/src/haystack_integrations/document_stores}/py.typed +0 -0
  21. {faiss_haystack-1.0.0/src/haystack_integrations → faiss_haystack-2.1.0/tests}/__init__.py +0 -0
@@ -0,0 +1,25 @@
1
+ # Changelog
2
+
3
+ ## [integrations/faiss-v2.0.0] - 2026-03-23
4
+
5
+ ### 🧪 Testing
6
+
7
+ - Test compatible integrations with python 3.14; update pyproject (#3001)
8
+ - `FaissDocumentStore` use Mixin tests (#3024)
9
+
10
+ ### ⚙️ CI
11
+
12
+ - Adding FAISS github workflow (#2879)
13
+
14
+ ### 🧹 Chores
15
+
16
+ - FAISS - small changes to improve consistency with the codebase (#2890)
17
+ - Standardize author mentions (#2897)
18
+ - Add ANN type annotations to faiss, fastembed, firecrawl, github, google_ai (#2988)
19
+ - Enforce ruff docstring rules (D102/D103/D205/D209/D213/D417/D419) in integrations 11-20 (#3009)
20
+
21
+ ### 🌀 Miscellaneous
22
+
23
+ - Add FAISS DocumentStore integration (#2844)
24
+
25
+ <!-- generated by git-cliff -->
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2023-present deepset GmbH
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -1,39 +1,39 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: faiss-haystack
3
- Version: 1.0.0
3
+ Version: 2.1.0
4
+ Summary: An integration of FAISS (library for efficient similarity search of dense vectors) with Haystack
4
5
  Project-URL: Documentation, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/faiss#readme
5
6
  Project-URL: Issues, https://github.com/deepset-ai/haystack-core-integrations/issues
6
7
  Project-URL: Source, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/faiss
7
- Author-email: Deepset <info@deepset.ai>
8
+ Author-email: deepset GmbH <info@deepset.ai>
8
9
  License-Expression: Apache-2.0
10
+ License-File: LICENSE.txt
9
11
  Classifier: Development Status :: 4 - Beta
10
12
  Classifier: License :: OSI Approved :: Apache Software License
11
13
  Classifier: Programming Language :: Python
12
14
  Classifier: Programming Language :: Python :: 3.10
13
15
  Classifier: Programming Language :: Python :: 3.11
14
16
  Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
15
19
  Classifier: Programming Language :: Python :: Implementation :: CPython
16
20
  Classifier: Programming Language :: Python :: Implementation :: PyPy
17
21
  Requires-Python: >=3.10
18
22
  Requires-Dist: faiss-cpu>=1.8.0
19
- Requires-Dist: haystack-ai>=2.24.0
23
+ Requires-Dist: haystack-ai>=2.26.1
20
24
  Requires-Dist: numpy<2,>=1.22; python_version < '3.13'
21
25
  Description-Content-Type: text/markdown
22
26
 
23
27
  # faiss-haystack
24
28
 
25
- This package provides a [FAISS](https://github.com/facebookresearch/faiss) document store for [Haystack](https://github.com/deepset-ai/haystack).
29
+ [![PyPI - Version](https://img.shields.io/pypi/v/faiss-haystack.svg)](https://pypi.org/project/faiss-haystack)
30
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/faiss-haystack.svg)](https://pypi.org/project/faiss-haystack)
26
31
 
27
- ## Installation
32
+ - [Integration page](https://haystack.deepset.ai/integrations/faiss)
33
+ - [Changelog](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/faiss/CHANGELOG.md)
28
34
 
29
- ```bash
30
- pip install faiss-haystack
31
- ```
35
+ ---
32
36
 
33
- ## Usage
37
+ ## Contributing
34
38
 
35
- ```python
36
- from haystack_integrations.document_stores.faiss import FAISSDocumentStore
37
-
38
- document_store = FAISSDocumentStore(index_path="my_index")
39
- ```
39
+ Refer to the general [Contribution Guidelines](https://github.com/deepset-ai/haystack-core-integrations/blob/main/CONTRIBUTING.md).
@@ -0,0 +1,13 @@
1
+ # faiss-haystack
2
+
3
+ [![PyPI - Version](https://img.shields.io/pypi/v/faiss-haystack.svg)](https://pypi.org/project/faiss-haystack)
4
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/faiss-haystack.svg)](https://pypi.org/project/faiss-haystack)
5
+
6
+ - [Integration page](https://haystack.deepset.ai/integrations/faiss)
7
+ - [Changelog](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/faiss/CHANGELOG.md)
8
+
9
+ ---
10
+
11
+ ## Contributing
12
+
13
+ Refer to the general [Contribution Guidelines](https://github.com/deepset-ai/haystack-core-integrations/blob/main/CONTRIBUTING.md).
@@ -5,12 +5,12 @@ build-backend = "hatchling.build"
5
5
  [project]
6
6
  name = "faiss-haystack"
7
7
  dynamic = ["version"]
8
- description = ''
8
+ description = 'An integration of FAISS (library for efficient similarity search of dense vectors) with Haystack'
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
11
11
  license = "Apache-2.0"
12
12
  keywords = []
13
- authors = [{ name = "Deepset", email = "info@deepset.ai" }]
13
+ authors = [{ name = "deepset GmbH", email = "info@deepset.ai" }]
14
14
  classifiers = [
15
15
  "License :: OSI Approved :: Apache Software License",
16
16
  "Development Status :: 4 - Beta",
@@ -18,11 +18,13 @@ classifiers = [
18
18
  "Programming Language :: Python :: 3.10",
19
19
  "Programming Language :: Python :: 3.11",
20
20
  "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ "Programming Language :: Python :: 3.14",
21
23
  "Programming Language :: Python :: Implementation :: CPython",
22
24
  "Programming Language :: Python :: Implementation :: PyPy",
23
25
  ]
24
26
  dependencies = [
25
- "haystack-ai>=2.24.0",
27
+ "haystack-ai>=2.26.1",
26
28
  "faiss-cpu>=1.8.0",
27
29
  "numpy>=1.22,<2; python_version < '3.13'",
28
30
  ]
@@ -48,7 +50,7 @@ installer = "uv"
48
50
  dependencies = ["haystack-pydoc-tools", "ruff"]
49
51
 
50
52
  [tool.hatch.envs.default.scripts]
51
- docs = ["pydoc-markdown pydoc/config_docusaurus.yml"]
53
+ docs = ["haystack-pydoc pydoc/config_docusaurus.yml"]
52
54
  fmt = "ruff check --fix {args}; ruff format {args}"
53
55
  fmt-check = "ruff check {args} && ruff format --check {args}"
54
56
 
@@ -59,13 +61,15 @@ dependencies = [
59
61
  "pytest-rerunfailures",
60
62
  "mypy",
61
63
  "pandas",
64
+ "pip", # needed for mypy to install type stubs
62
65
  ]
63
66
 
64
67
  [tool.hatch.envs.test.scripts]
65
68
  unit = 'pytest -m "not integration" {args:tests}'
66
69
  integration = 'pytest -m "integration" {args:tests}'
67
70
  all = 'pytest {args:tests}'
68
- cov-retry = 'pytest --cov=haystack_integrations --reruns 3 --reruns-delay 30 -x {args:tests}'
71
+ unit-cov-retry = 'pytest --cov=haystack_integrations --reruns 3 --reruns-delay 30 -x -m "not integration" {args:tests}'
72
+ integration-cov-append-retry = 'pytest --cov=haystack_integrations --cov-append --reruns 3 --reruns-delay 30 -x -m "integration" {args:tests}'
69
73
 
70
74
  types = "mypy -p haystack_integrations.document_stores.faiss -p haystack_integrations.components.retrievers.faiss {args}"
71
75
 
@@ -75,8 +79,12 @@ non_interactive = true
75
79
  check_untyped_defs = true
76
80
  disallow_incomplete_defs = true
77
81
 
78
- [tool.hatch.metadata]
79
- allow-direct-references = true
82
+ [[tool.mypy.overrides]]
83
+ module = [
84
+ # faiss does not provide types
85
+ "faiss.*",
86
+ ]
87
+ ignore_missing_imports = true
80
88
 
81
89
  [tool.ruff]
82
90
  line-length = 120
@@ -84,9 +92,17 @@ line-length = 120
84
92
  [tool.ruff.lint]
85
93
  select = [
86
94
  "A",
95
+ "ANN",
87
96
  "ARG",
88
97
  "B",
89
98
  "C",
99
+ "D102", # Missing docstring in public method
100
+ "D103", # Missing docstring in public function
101
+ "D205", # 1 blank line required between summary line and description
102
+ "D209", # Closing triple quotes go to new line
103
+ "D213", # summary lines must be positioned on the second physical line of the docstring
104
+ "D417", # Missing argument descriptions in the docstring
105
+ "D419", # Docstring is empty
90
106
  "DTZ",
91
107
  "E",
92
108
  "EM",
@@ -124,10 +140,13 @@ ignore = [
124
140
  "PLR0912",
125
141
  "PLR0913",
126
142
  "PLR0915",
143
+ "PLR0917",
127
144
  # Ignore unused params
128
145
  "ARG002",
129
146
  # Allow assertions
130
147
  "S101",
148
+ # Allow `Any` - used legitimately for dynamic types and SDK boundaries
149
+ "ANN401",
131
150
  ]
132
151
  exclude = ["example"]
133
152
 
@@ -139,12 +158,13 @@ ban-relative-imports = "parents"
139
158
 
140
159
  [tool.ruff.lint.per-file-ignores]
141
160
  # Tests can use magic values, assertions, and relative imports
142
- "tests/**/*" = ["PLR2004", "S101", "TID252"]
161
+ "tests/**/*" = ["D", "PLR2004", "S101", "TID252", "ANN"]
143
162
  "example/**/*" = ["T201"]
144
163
 
145
164
  [tool.coverage.run]
146
165
  source = ["haystack_integrations"]
147
166
  branch = true
167
+ relative_files = true
148
168
  parallel = false
149
169
 
150
170
 
@@ -156,4 +176,5 @@ exclude_lines = ["no cov", "if __name__ == .__main__.:", "if TYPE_CHECKING:"]
156
176
 
157
177
  [tool.pytest.ini_options]
158
178
  minversion = "6.0"
179
+ addopts = "--strict-markers"
159
180
  markers = ["integration: integration tests"]
@@ -20,7 +20,9 @@ class FAISSEmbeddingRetriever:
20
20
  Example usage:
21
21
  ```python
22
22
  from haystack import Document, Pipeline
23
- from haystack.components.embedders import SentenceTransformersTextEmbedder, SentenceTransformersDocumentEmbedder
23
+ # Requires: pip install sentence-transformers-haystack
24
+ from haystack_integrations.components.embedders.sentence_transformers import SentenceTransformersTextEmbedder
25
+ from haystack_integrations.components.embedders.sentence_transformers import SentenceTransformersDocumentEmbedder
24
26
  from haystack.document_stores.types import DuplicatePolicy
25
27
 
26
28
  from haystack_integrations.document_stores.faiss import FAISSDocumentStore
@@ -35,7 +37,6 @@ class FAISSEmbeddingRetriever:
35
37
  ]
36
38
 
37
39
  document_embedder = SentenceTransformersDocumentEmbedder()
38
- document_embedder.warm_up()
39
40
  documents_with_embeddings = document_embedder.run(documents)["documents"]
40
41
 
41
42
  document_store.write_documents(documents_with_embeddings, policy=DuplicatePolicy.OVERWRITE)
@@ -59,8 +60,10 @@ class FAISSEmbeddingRetriever:
59
60
  filters: dict[str, Any] | None = None,
60
61
  top_k: int = 10,
61
62
  filter_policy: str | FilterPolicy = FilterPolicy.REPLACE,
62
- ):
63
+ ) -> None:
63
64
  """
65
+ Initialize FAISSEmbeddingRetriever.
66
+
64
67
  :param document_store: An instance of `FAISSDocumentStore`.
65
68
  :param filters: Filters applied to the retrieved Documents at initialisation time. At runtime, these are merged
66
69
  with any runtime filters according to the `filter_policy`.
@@ -9,7 +9,6 @@ from dataclasses import replace
9
9
  from pathlib import Path
10
10
  from typing import Any
11
11
 
12
- import faiss # type: ignore[import-untyped]
13
12
  import numpy as np
14
13
  from haystack import default_from_dict, default_to_dict
15
14
  from haystack.dataclasses import Document
@@ -17,6 +16,8 @@ from haystack.document_stores.errors import DocumentStoreError, DuplicateDocumen
17
16
  from haystack.document_stores.types import DuplicatePolicy
18
17
  from haystack.errors import FilterError
19
18
 
19
+ import faiss
20
+
20
21
  logger = logging.getLogger(__name__)
21
22
 
22
23
 
@@ -33,7 +34,7 @@ class FAISSDocumentStore:
33
34
  index_path: str | None = None,
34
35
  index_string: str = "Flat",
35
36
  embedding_dim: int = 768,
36
- ):
37
+ ) -> None:
37
38
  """
38
39
  Initializes the FAISSDocumentStore.
39
40
 
@@ -60,7 +61,7 @@ class FAISSDocumentStore:
60
61
  else:
61
62
  self._create_new_index()
62
63
 
63
- def _create_new_index(self):
64
+ def _create_new_index(self) -> None:
64
65
  """Creates a new FAISS index."""
65
66
  try:
66
67
  # We use IndexIDMap to support add_with_ids
@@ -457,11 +458,7 @@ class FAISSDocumentStore:
457
458
  """
458
459
  values = []
459
460
  for doc in self.documents.values():
460
- val = (
461
- FAISSDocumentStore._get_doc_value(doc, field_name)
462
- if not field_name.startswith("meta.")
463
- else doc.meta.get(field_name[5:])
464
- )
461
+ val = FAISSDocumentStore._get_doc_value(doc, field_name)
465
462
  if val is not None:
466
463
  values.append(val)
467
464
 
@@ -470,41 +467,71 @@ class FAISSDocumentStore:
470
467
 
471
468
  return {"min": min(values), "max": max(values)}
472
469
 
473
- def get_metadata_field_unique_values(self, field_name: str) -> list[Any]:
474
- """
475
- Returns all unique values for a specific metadata field.
476
-
477
- :param field_name: The name of the metadata field.
478
- :returns: A list of unique values for the specified field.
470
+ def get_metadata_field_unique_values(
471
+ self,
472
+ metadata_field: str,
473
+ search_term: str | None = None,
474
+ from_: int = 0,
475
+ size: int = 10,
476
+ filters: dict[str, Any] | None = None,
477
+ ) -> tuple[list[Any], int]:
478
+ """
479
+ Returns unique values for a metadata field, optionally filtered by a search term, with pagination.
480
+
481
+ :param metadata_field: The metadata field to get unique values for. Can include or omit the "meta." prefix.
482
+ :param search_term: Optional search term to filter values, matched as a case-insensitive substring
483
+ against the metadata field's value.
484
+ :param from_: The offset to start returning values from (for pagination).
485
+ :param size: The maximum number of unique values to return.
486
+ :param filters: Optional filters to restrict the documents considered.
487
+ :returns: A tuple containing list of unique values (in their original type) and total count of
488
+ unique values.
479
489
  """
480
- values = set()
481
- for doc in self.documents.values():
482
- val = (
483
- FAISSDocumentStore._get_doc_value(doc, field_name)
484
- if not field_name.startswith("meta.")
485
- else doc.meta.get(field_name[5:])
486
- )
490
+ values = []
491
+ for doc in self.filter_documents(filters=filters):
492
+ val = FAISSDocumentStore._get_doc_value(doc, metadata_field)
487
493
  if val is not None:
488
- values.add(val)
489
- return list(values)
494
+ values.append(val)
495
+
496
+ if search_term:
497
+ search_term_lower = search_term.lower()
498
+ values = [val for val in values if search_term_lower in str(val).lower()]
499
+
500
+ # Values of different types can be equal in Python (`1 == True`, `1 == 1.0`), so a plain set
501
+ # would silently merge them. Dedupe by (type, value) instead to keep them distinct.
502
+ seen: set[tuple[type, Any]] = set()
503
+ unique_values = []
504
+ for val in values:
505
+ dedup_key = (type(val), val)
506
+ if dedup_key not in seen:
507
+ seen.add(dedup_key)
508
+ unique_values.append(val)
509
+ sorted_values = sorted(unique_values, key=str)
510
+ total_count = len(sorted_values)
511
+ end = from_ + size
512
+ paginated_values = sorted_values[from_:end]
513
+
514
+ return paginated_values, total_count
490
515
 
491
- def count_unique_metadata_by_filter(self, filters: dict[str, Any], fields: list[str]) -> dict[str, int]:
516
+ def count_unique_metadata_by_filter(self, filters: dict[str, Any], metadata_fields: list[str]) -> dict[str, int]:
492
517
  """
493
518
  Returns a count of unique values for multiple metadata fields, optionally scoped by a filter.
494
519
 
495
520
  :param filters: A dictionary of filters to apply.
496
- :param fields: A list of metadata field names to count unique values for.
521
+ :param metadata_fields: A list of metadata field names to count unique values for.
497
522
  :returns: A dictionary mapping each field name to the count of its unique values.
498
523
  """
499
524
  filtered_docs = self.filter_documents(filters)
500
525
  counts = {}
501
526
 
502
- for field in fields:
503
- unique_vals = set()
527
+ for field in metadata_fields:
528
+ # Values of different types can be equal in Python (`1 == True`, `1 == 1.0`), so a plain
529
+ # set would silently merge them. Dedupe by (type, value) instead to keep them distinct.
530
+ unique_vals: set[tuple[type, Any]] = set()
504
531
  for doc in filtered_docs:
505
532
  val = FAISSDocumentStore._get_doc_value(doc, field)
506
533
  if val is not None:
507
- unique_vals.add(val)
534
+ unique_vals.add((type(val), val))
508
535
  counts[field] = len(unique_vals)
509
536
 
510
537
  return dict(counts)
@@ -4,19 +4,74 @@
4
4
 
5
5
  import pytest
6
6
  from haystack.dataclasses import Document
7
+ from haystack.document_stores.errors import DocumentStoreError, DuplicateDocumentError
8
+ from haystack.document_stores.types import DuplicatePolicy
7
9
  from haystack.errors import FilterError
8
10
  from haystack.testing.document_store import (
11
+ CountDocumentsByFilterTest,
9
12
  CountDocumentsTest,
13
+ CountUniqueMetadataByFilterTest,
10
14
  DeleteAllTest,
11
15
  DeleteByFilterTest,
12
16
  DeleteDocumentsTest,
13
17
  FilterDocumentsTest,
18
+ GetMetadataFieldMinMaxTest,
19
+ GetMetadataFieldsInfoTest,
20
+ GetMetadataFieldUniqueValuesTest,
14
21
  UpdateByFilterTest,
15
22
  )
16
23
 
17
24
  from haystack_integrations.document_stores.faiss import FAISSDocumentStore
18
25
 
19
26
 
27
+ class TestFAISSDocumentStoreUnit:
28
+ def test_create_new_index_with_invalid_factory_raises(self):
29
+ with pytest.raises(DocumentStoreError, match="Could not create FAISS index"):
30
+ FAISSDocumentStore(index_string="NotARealIndex", embedding_dim=3)
31
+
32
+ def test_get_index_or_raise_when_index_is_none(self):
33
+ ds = FAISSDocumentStore(embedding_dim=3)
34
+ ds.index = None
35
+ with pytest.raises(DocumentStoreError, match="FAISS index has not been initialized"):
36
+ ds._get_index_or_raise()
37
+
38
+ @pytest.mark.parametrize(
39
+ "bad_input",
40
+ [
41
+ "a string",
42
+ b"some bytes",
43
+ 123,
44
+ [Document(content="ok"), "not a document"],
45
+ ],
46
+ )
47
+ def test_write_documents_rejects_invalid_input(self, bad_input):
48
+ ds = FAISSDocumentStore(embedding_dim=3)
49
+ with pytest.raises(ValueError, match="iterable of objects of type Document"):
50
+ ds.write_documents(bad_input)
51
+
52
+ def test_write_documents_fail_policy_raises_on_duplicate(self):
53
+ ds = FAISSDocumentStore(embedding_dim=3)
54
+ ds.write_documents([Document(id="dup", content="first")])
55
+ with pytest.raises(DuplicateDocumentError, match="already exists"):
56
+ ds.write_documents([Document(id="dup", content="second")], policy=DuplicatePolicy.FAIL)
57
+
58
+ @pytest.mark.parametrize(
59
+ ("filters", "error_match"),
60
+ [
61
+ ({"operator": "OR"}, "Missing 'conditions' for OR operator"),
62
+ ({"operator": "AND"}, "Missing 'conditions' for AND operator"),
63
+ ({"operator": "NOT"}, "Missing 'conditions' for NOT operator"),
64
+ ({"operator": "==", "field": 42, "value": "x"}, "'field' in filter condition must be a string"),
65
+ ],
66
+ )
67
+ def test_check_condition_invalid_structure_raises_filter_error(self, filters, error_match):
68
+ ds = FAISSDocumentStore(embedding_dim=3)
69
+ ds.write_documents([Document(content="test", meta={"category": "A"})])
70
+ with pytest.raises(FilterError, match=error_match):
71
+ ds.filter_documents(filters=filters)
72
+
73
+
74
+ @pytest.mark.integration
20
75
  class TestFAISSDocumentStore(
21
76
  CountDocumentsTest,
22
77
  DeleteDocumentsTest,
@@ -24,20 +79,23 @@ class TestFAISSDocumentStore(
24
79
  UpdateByFilterTest,
25
80
  DeleteAllTest,
26
81
  DeleteByFilterTest,
82
+ CountDocumentsByFilterTest,
83
+ CountUniqueMetadataByFilterTest,
84
+ GetMetadataFieldsInfoTest,
85
+ GetMetadataFieldMinMaxTest,
86
+ GetMetadataFieldUniqueValuesTest,
27
87
  ):
28
88
  @pytest.fixture
29
89
  def document_store(self, tmp_path):
30
90
  return FAISSDocumentStore(index_path=str(tmp_path / "test_index"))
31
91
 
32
92
  def test_write_documents(self, document_store):
33
-
34
93
  doc = Document(content="test")
35
94
  document_store.write_documents([doc])
36
95
  assert document_store.count_documents() == 1
37
96
  assert document_store.filter_documents()[0].id == doc.id
38
97
 
39
98
  def test_persistence(self, tmp_path):
40
-
41
99
  path = tmp_path / "persistent_index"
42
100
  ds = FAISSDocumentStore(index_path=str(path), embedding_dim=3)
43
101
 
@@ -52,7 +110,6 @@ class TestFAISSDocumentStore(
52
110
  assert ds_loaded.filter_documents()[0].embedding == [0.1, 0.2, 0.3]
53
111
 
54
112
  def test_persistence_no_embeddings(self, tmp_path):
55
-
56
113
  path = tmp_path / "persistent_index_no_embed"
57
114
  ds = FAISSDocumentStore(index_path=str(path), embedding_dim=3)
58
115
 
@@ -73,7 +130,6 @@ class TestFAISSDocumentStore(
73
130
  ds.load(path)
74
131
 
75
132
  def test_search_with_and_without_filters(self, document_store):
76
-
77
133
  # Setup documents with missing/varied embeddings to test edge cases
78
134
  doc1 = Document(content="test1", embedding=[0.1, 0.2, 0.3], meta={"category": "A"})
79
135
  doc2 = Document(content="test2", embedding=[0.4, 0.5, 0.6], meta={"category": "B"})
@@ -97,7 +153,6 @@ class TestFAISSDocumentStore(
97
153
 
98
154
  def test_to_dict_from_dict(self):
99
155
  ds = FAISSDocumentStore(index_path="test_index", index_string="Flat", embedding_dim=128)
100
-
101
156
  data = ds.to_dict()
102
157
  assert data["type"] == "haystack_integrations.document_stores.faiss.document_store.FAISSDocumentStore"
103
158
  assert data["init_parameters"]["index_path"] == "test_index"
@@ -109,50 +164,10 @@ class TestFAISSDocumentStore(
109
164
  assert ds_loaded.index_string == "Flat"
110
165
  assert ds_loaded.embedding_dim == 128
111
166
 
112
- def test_count_documents_by_filter(self, document_store):
113
-
114
- docs = [
115
- Document(content="test1", meta={"category": "A"}),
116
- Document(content="test2", meta={"category": "B"}),
117
- Document(content="test3", meta={"category": "A"}),
118
- ]
119
- document_store.write_documents(docs)
120
-
121
- count = document_store.count_documents_by_filter(
122
- filters={"field": "meta.category", "operator": "==", "value": "A"}
123
- )
124
- assert count == 2
125
-
126
- def test_get_metadata_fields_info(self, document_store):
127
-
128
- docs = [Document(content="test1", meta={"category": "A", "count": 1, "is_active": True})]
129
- document_store.write_documents(docs)
130
-
131
- info = document_store.get_metadata_fields_info()
132
- assert "category" in info
133
- assert info["category"]["type"] == "keyword"
134
- assert "count" in info
135
- assert info["count"]["type"] == "long"
136
- assert "is_active" in info
137
- assert info["is_active"]["type"] == "boolean"
138
-
139
- def test_count_unique_metadata_by_filter(self, document_store):
140
-
141
- docs = [
142
- Document(content="test1", meta={"category": "A", "status": "active"}),
143
- Document(content="test2", meta={"category": "B", "status": "inactive"}),
144
- Document(content="test3", meta={"category": "A", "status": "active"}),
145
- ]
146
- document_store.write_documents(docs)
147
-
148
- counts = document_store.count_unique_metadata_by_filter(
149
- filters={"field": "meta.category", "operator": "==", "value": "A"}, fields=["meta.status"]
150
- )
151
- assert "meta.status" in counts
152
- assert counts["meta.status"] == 1 # Only "active" status for category A
153
-
154
167
  def test_not_filter_with_empty_conditions_raises_filter_error(self, document_store):
155
168
  document_store.write_documents([Document(content="test", meta={"category": "A"})])
156
-
157
169
  with pytest.raises(FilterError, match="NOT operator expects at least one condition"):
158
170
  document_store.filter_documents(filters={"operator": "NOT", "conditions": []})
171
+
172
+ # get_metadata_field_unique_values behavior (search term, pagination, meta-prefix handling, non-string
173
+ # type preservation, filter restriction) is covered by the inherited GetMetadataFieldUniqueValuesTest mixin.
@@ -31,6 +31,12 @@ def populated_store(document_store):
31
31
  return document_store
32
32
 
33
33
 
34
+ def test_invalid_document_store_type():
35
+ with pytest.raises(ValueError, match="document_store must be an instance of FAISSDocumentStore"):
36
+ FAISSEmbeddingRetriever(document_store="not_a_store") # type: ignore[arg-type]
37
+
38
+
39
+ @pytest.mark.integration
34
40
  class TestFAISSEmbeddingRetriever:
35
41
  def test_run_with_query_embedding_only(self, populated_store):
36
42
  retriever = FAISSEmbeddingRetriever(document_store=populated_store, top_k=2)
@@ -112,10 +118,6 @@ class TestFAISSEmbeddingRetriever:
112
118
  assert len(result["documents"]) >= 1
113
119
  assert all(d.meta["category"] == "A" for d in result["documents"])
114
120
 
115
- def test_invalid_document_store_type(self):
116
- with pytest.raises(ValueError, match="document_store must be an instance of FAISSDocumentStore"):
117
- FAISSEmbeddingRetriever(document_store="not_a_store") # type: ignore[arg-type]
118
-
119
121
  def test_run_in_pipeline(self, populated_store):
120
122
  """End-to-end: FAISSEmbeddingRetriever wired into a Haystack Pipeline."""
121
123
  retriever = FAISSEmbeddingRetriever(document_store=populated_store, top_k=2)
@@ -1,17 +0,0 @@
1
- # faiss-haystack
2
-
3
- This package provides a [FAISS](https://github.com/facebookresearch/faiss) document store for [Haystack](https://github.com/deepset-ai/haystack).
4
-
5
- ## Installation
6
-
7
- ```bash
8
- pip install faiss-haystack
9
- ```
10
-
11
- ## Usage
12
-
13
- ```python
14
- from haystack_integrations.document_stores.faiss import FAISSDocumentStore
15
-
16
- document_store = FAISSDocumentStore(index_path="my_index")
17
- ```
@@ -1,3 +0,0 @@
1
- # SPDX-FileCopyrightText: 2023-present deepset GmbH <info@deepset.ai>
2
- #
3
- # SPDX-License-Identifier: Apache-2.0
@@ -1,3 +0,0 @@
1
- # SPDX-FileCopyrightText: 2023-present deepset GmbH <info@deepset.ai>
2
- #
3
- # SPDX-License-Identifier: Apache-2.0
File without changes