Skip to content

armgit / txtai

Public Imported from GitHub
0

💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows

Add additional indexes for embeddings, closes #515

davidmezzettiea7c811b821a
diff --git a/src/python/txtai/embeddings/__init__.py b/src/python/txtai/embeddings/__init__.py
index 0a01df60..a5ed3d6e 100644
--- a/src/python/txtai/embeddings/__init__.py
+++ b/src/python/txtai/embeddings/__init__.py
@@ -2,14 +2,6 @@
Embeddings imports
"""
-from .autoid import AutoId
-from .action import Action
from .base import Embeddings
-from .documents import Documents
-from .explain import Explain
-from .functions import *
-from .query import Query
-from .reducer import Reducer
-from .search import Search
-from .terms import Terms
-from .transform import Transform
+from .index import *
+from .search import *
diff --git a/src/python/txtai/embeddings/base.py b/src/python/txtai/embeddings/base.py
index af78fe8f..359d11b9 100644
--- a/src/python/txtai/embeddings/base.py
+++ b/src/python/txtai/embeddings/base.py
@@ -19,18 +19,11 @@ from ..scoring import ScoringFactory
from ..vectors import VectorsFactory
from ..version import __pickle__
-from .action import Action
-from .explain import Explain
-from .functions import Functions
-from .reducer import Reducer
-from .query import Query
-from .search import Search
-from .stream import Stream
-from .terms import Terms
-from .transform import Transform
-
-
-# pylint: disable=R0904
+from .index import Action, Functions, Indexes, Reducer, Stream, Transform
+from .search import Explain, Query, Search, Terms
+
+
+# pylint: disable=C0302,R0904
class Embeddings:
"""
Embeddings is the engine that delivers semantic search. Data is transformed into embeddings vectors where similar concepts
@@ -39,12 +32,13 @@ class Embeddings:
"""
# pylint: disable = W0231
- def __init__(self, config=None, **kwargs):
+ def __init__(self, config=None, models=None, **kwargs):
"""
Creates a new embeddings index. Embeddings indexes are thread-safe for read operations but writes must be synchronized.
Args:
config: embeddings configuration
+ models: models cache, used for model sharing between embeddings
kwargs: additional configuration as keyword args
"""
@@ -78,6 +72,12 @@ class Embeddings:
# Index archive
self.archive = None
+ # Subindexes for this embeddings instance
+ self.indexes = None
+
+ # Models cache
+ self.models = models
+
# Merge configuration into single dictionary
config = {**config, **kwargs} if config and kwargs else kwargs if kwargs else config
@@ -142,6 +142,10 @@ class Embeddings:
if self.issparse():
self.scoring.index()
+ # Index subindexes
+ if self.indexes:
+ self.indexes.index()
+
# Index graph, if necessary
if self.graph:
self.graph.index(Search(self, True), self.batchsimilarity)
@@ -188,6 +192,10 @@ class Embeddings:
if self.issparse():
self.scoring.upsert()
+ # Subindexes upsert, if necessary
+ if self.indexes:
+ self.indexes.upsert()
+
# Graph upsert, if necessary
if self.graph:
self.graph.upsert(Search(self, True), self.batchsimilarity)
@@ -242,6 +250,10 @@ class Embeddings:
if self.issparse():
self.scoring.delete(indices)
+ # Delete ids from subindexes
+ if self.indexes:
+ self.indexes.delete(indices)
+
# Delete ids from graph
if self.graph:
self.graph.delete(indices)
@@ -327,9 +339,19 @@ class Embeddings:
number of elements in this embeddings index
"""
- return self.ann.count() if self.ann else self.scoring.count() if self.scoring else 0
+ if self.ann:
+ return self.ann.count()
+ if self.scoring:
+ return self.scoring.count()
+ if self.database:
+ return self.database.count()
+ if self.config.get("ids"):
+ return len([uid for uid in self.config["ids"] if uid is not None])
- def search(self, query, limit=None, weights=None):
+ # Default to 0 when no suitable method found
+ return 0
+
+ def search(self, query, limit=None, weights=None, index=None):
"""
Finds documents most similar to the input queries. This method will run either an index search
or an index + database search depending on if a database is available.
@@ -338,15 +360,16 @@ class Embeddings:
query: input query
limit: maximum results
weights: hybrid score weights, if applicable
+ index: index name, if applicable
Returns:
list of (id, score) for index search, list of dict for an index+database search
"""
- results = self.batchsearch([query], limit, weights)
+ results = self.batchsearch([query], limit, weights, index)
return results[0] if results else results
- def batchsearch(self, queries, limit=None, weights=None):
+ def batchsearch(self, queries, limit=None, weights=None, index=None):
"""
Finds documents most similar to the input queries. This method will run either an index search
or an index + database search depending on if a database is available.
@@ -355,12 +378,13 @@ class Embeddings:
queries: input queries
limit: maximum results
weights: hybrid score weights, if applicable
+ index: index name, if applicable
Returns:
list of (id, score) per query for index search, list of dict per query for an index+database search
"""
- return Search(self)(queries, limit, weights)
+ return Search(self)(queries, limit, weights, index)
def similarity(self, query, data):
"""
@@ -525,16 +549,21 @@ class Embeddings:
if self.database:
self.database.load(f"{path}/documents")
- # Graph network - stores relationships
- self.graph = self.creategraph()
- if self.graph:
- self.graph.load(f"{path}/graph")
-
# Sparse vectors - stores term sparse arrays
self.scoring = self.createscoring()
if self.scoring:
self.scoring.load(f"{path}/scoring")
+ # Subindexes
+ self.indexes = self.createindexes()
+ if self.indexes:
+ self.indexes.load(f"{path}/indexes")
+
+ # Graph network - stores relationships
+ self.graph = self.creategraph()
+ if self.graph:
+ self.graph.load(f"{path}/graph")
+
# Dense vectors - transforms data to embeddings vectors
self.model = self.loadvectors()
@@ -580,14 +609,18 @@ class Embeddings:
if self.database:
self.database.save(f"{path}/documents")
- # Save graph
- if self.graph:
- self.graph.save(f"{path}/graph")
-
# Save scoring index
if self.scoring:
self.scoring.save(f"{path}/scoring")
+ # Save subindexes
+ if self.indexes:
+ self.indexes.save(f"{path}/indexes")
+
+ # Save graph
+ if self.graph:
+ self.graph.save(f"{path}/graph")
+
# If this is an archive, save it
if apath:
self.archive.save(apath)
@@ -602,8 +635,8 @@ class Embeddings:
Closes this embeddings index and frees all resources.
"""
- self.config, self.reducer, self.query, self.model = None, None, None, None
- self.ann, self.graph, self.archive = None, None, None
+ self.ann, self.config, self.graph, self.archive = None, None, None, None
+ self.reducer, self.query, self.model, self.models = None, None, None, None
# Close database connection if open
if self.database:
@@ -615,6 +648,11 @@ class Embeddings:
self.scoring.close()
self.scoring = None
+ # Close indexes if open
+ if self.indexes:
+ self.indexes.close()
+ self.indexes = None
+
def info(self):
"""
Prints the current embeddings index configuration.
@@ -702,14 +740,17 @@ class Embeddings:
# Reset archive since this is a new index
self.archive = None
- # Create graph, if necessary
- self.graph = self.creategraph()
-
# Create scoring only if term indexing is enabled
scoring = self.config.get("scoring")
if scoring and isinstance(scoring, dict) and self.config["scoring"].get("terms"):
self.scoring = self.createscoring()
+ # Create subindexes, if necessary
+ self.indexes = self.createindexes()
+
+ # Create graph, if necessary
+ self.graph = self.creategraph()
+
def defaults(self):
"""
Apply default parameters to current configuration.
@@ -722,15 +763,26 @@ class Embeddings:
# Expand sparse index shortcuts
if not self.config.get("scoring") and any(self.config.get(key) for key in ["keyword", "hybrid"]):
- self.config["scoring"] = {"method": "bm25", "terms": True}
+ self.config["scoring"] = {"method": "bm25", "terms": True, "normalize": True}
- # Add default path if configuration available and this isn't a keyword index
- if not self.model and not self.config.get("keyword"):
+ # Check if default model should be loaded
+ if not self.model and self.defaultallowed():
self.config["path"] = "sentence-transformers/all-MiniLM-L6-v2"
# Load dense vectors model
self.model = self.loadvectors()
+ def defaultallowed(self):
+ """
+ Tests if this embeddings instance can use a default model if not otherwise provided.
+
+ Returns:
+ True if a default model is allowed, False otherwise
+ """
+
+ params = [("keyword", False), ("defaults", True)]
+ return all(self.config.get(key, default) == default for key, default in params)
+
def loadconfig(self, path):
"""
Loads index configuration. This method supports both config pickle files and config.json files.
@@ -795,7 +847,23 @@ class Embeddings:
vector model
"""
- return VectorsFactory.create(self.config, self.scoring)
+ # Create model cache if subindexes are enabled
+ if "indexes" in self.config and self.models is None:
+ self.models = {}
+
+ # Model path
+ path = self.config.get("path")
+
+ # Check if model is cached
+ if self.models and path in self.models:
+ return self.models[path]
+
+ # Load and store uncached model
+ model = VectorsFactory.create(self.config, self.scoring)
+ if self.models is not None and path:
+ self.models[path] = model
+
+ return model
def loadquery(self):
"""
@@ -855,7 +923,7 @@ class Embeddings:
new ANN, if enabled in config
"""
- return ANNFactory.create(self.config) if self.config.get("path") or not self.config.get("keyword") else None
+ return ANNFactory.create(self.config) if self.config.get("path") or self.defaultallowed() else None
def createdatabase(self):
"""
@@ -894,6 +962,26 @@ class Embeddings:
return None
+ def createindexes(self):
+ """
+ Creates subindexes from config.
+
+ Returns:
+ list of subindexes
+ """
+
+ # Load subindexes
+ if "indexes" in self.config:
+ indexes = {}
+ for index, config in self.config["indexes"].items():
+ # Create index with shared model cache
+ indexes[index] = Embeddings(config, models=self.models)
+
+ # Wrap as Indexes object
+ return Indexes(self, indexes)
+
+ return None
+
def createscoring(self):
"""
Creates a scoring from config.
diff --git a/src/python/txtai/embeddings/index/__init__.py b/src/python/txtai/embeddings/index/__init__.py
new file mode 100644
index 00000000..a68599e1
--- /dev/null
+++ b/src/python/txtai/embeddings/index/__init__.py
@@ -0,0 +1,13 @@
+"""
+Index imports
+"""
+
+
+from .action import Action
+from .autoid import AutoId
+from .documents import Documents
+from .functions import Functions
+from .indexes import Indexes
+from .reducer import Reducer
+from .stream import Stream
+from .transform import Transform
diff --git a/src/python/txtai/embeddings/action.py b/src/python/txtai/embeddings/index/action.py
similarity index 100%
rename from src/python/txtai/embeddings/action.py
rename to src/python/txtai/embeddings/index/action.py
diff --git a/src/python/txtai/embeddings/autoid.py b/src/python/txtai/embeddings/index/autoid.py
similarity index 100%
rename from src/python/txtai/embeddings/autoid.py
rename to src/python/txtai/embeddings/index/autoid.py
diff --git a/src/python/txtai/embeddings/documents.py b/src/python/txtai/embeddings/index/documents.py
similarity index 98%
rename from src/python/txtai/embeddings/documents.py
rename to src/python/txtai/embeddings/index/documents.py
index 192af253..b2402b7a 100644
--- a/src/python/txtai/embeddings/documents.py
+++ b/src/python/txtai/embeddings/index/documents.py
@@ -6,7 +6,7 @@ import os
import pickle
import tempfile
-from ..version import __pickle__
+from ...version import __pickle__
class Documents:
diff --git a/src/python/txtai/embeddings/functions.py b/src/python/txtai/embeddings/index/functions.py
similarity index 100%
rename from src/python/txtai/embeddings/functions.py
rename to src/python/txtai/embeddings/index/functions.py
diff --git a/src/python/txtai/embeddings/index/indexes.py b/src/python/txtai/embeddings/index/indexes.py
new file mode 100644
index 00000000..ee05376c
--- /dev/null
+++ b/src/python/txtai/embeddings/index/indexes.py
@@ -0,0 +1,177 @@
+"""
+Indexes module
+"""
+
+import os
+
+from .documents import Documents
+
+
+class Indexes:
+ """
+ Manages a collection of subindexes for an embeddings instance.
+ """
+
+ def __init__(self, embeddings, indexes):
+ """
+ Creates a new indexes instance.
+
+ Args:
+ embeddings: embeddings instance
+ indexes: list of subindexes to add
+ """
+
+ self.embeddings = embeddings
+ self.indexes = indexes
+
+ self.documents = None
+
+ # Transform columns
+ columns = embeddings.config.get("columns", {})
+ self.text = columns.get("text", "text")
+ self.object = columns.get("object", "object")
+
+ # Check if top-level indexing is enabled for this embeddings instance
+ self.indexing = embeddings.model or embeddings.scoring
+
+ def __contains__(self, name):
+ """
+ Returns True if name is in this instance, False otherwise.
+
+ Returns:
+ True if name is in this instance, False otherwise
+ """
+
+ return name in self.indexes
+
+ def __getitem__(self, name):
+ """
+ Looks up an index by name.
+
+ Args:
+ name: index name
+
+ Returns:
+ index
+ """
+
+ return self.indexes[name]
+
+ def __getattr__(self, name):
+ """
+ Looks up an index by attribute name.
+
+ Args:
+ name: index name
+
+ Returns:
+ index
+ """
+
+ try:
+ return self.indexes[name]
+ except Exception as ex:
+ raise AttributeError(ex) from ex
+
+ def default(self):
+ """
+ Gets the default/first index.
+
+ Returns:
+ default index
+ """
+
+ return list(self.indexes.keys())[0]
+
+ def insert(self, documents, index=None):
+ """
+ Inserts a batch of documents into each subindex.
+
+ Args:
+ documents: list of (id, data, tags)
+ index: indexid offset
+ """
+
+ if not self.documents:
+ self.documents = Documents()
+
+ # Create batch containing documents added to parent index
+ batch = []
+ for _, document, _ in documents:
+ # Add to documents collection if text or object field is set
+ parent = document
+ if isinstance(parent, dict):
+ parent = parent.get(self.text, document.get(self.object))
+
+ # Add if field is available or top-level indexing is disabled
+ if parent is not None or not self.indexing:
+ batch.append((index, document, None))
+ index += 1
+
+ # Add filtered documents batch
+ self.documents.add(batch)
+
+ def delete(self, ids):
+ """
+ Deletes ids from each subindex.
+
+ Args:
+ ids: list of ids to delete
+ """
+
+ for index in self.indexes.values():
+ index.delete(ids)
+
+ def index(self):
+ """
+ Builds each subindex.
+ """
+
+ for index in self.indexes.values():
+ index.index(self.documents)
+
+ # Reset document stream
+ self.documents.close()
+ self.documents = None
+
+ def upsert(self):
+ """
+ Runs upsert for each subindex.
+ """
+
+ for index in self.indexes.values():
+ index.upsert(self.documents)
+
+ # Reset document stream
+ self.documents.close()
+ self.documents = None
+
+ def load(self, path):
+ """
+ Loads each subindex from path.
+
+ Args:
+ path: directory path to load subindexes
+ """
+
+ for name, index in self.indexes.items():
+ index.load(os.path.join(path, name))
+
+ def save(self, path):
+ """
+ Saves each subindex to path.
+
+ Args:
+ path: directory path to save subindexes
+ """
+
+ for name, index in self.indexes.items():
+ index.save(os.path.join(path, name))
+
+ def close(self):
+ """
+ Close and free resources used by this instance.
+ """
+
+ for index in self.indexes.values():
+ index.close()
diff --git a/src/python/txtai/embeddings/reducer.py b/src/python/txtai/embeddings/index/reducer.py
similarity index 98%
rename from src/python/txtai/embeddings/reducer.py
rename to src/python/txtai/embeddings/index/reducer.py
index 6dfe8de0..e4770bcd 100644
--- a/src/python/txtai/embeddings/reducer.py
+++ b/src/python/txtai/embeddings/index/reducer.py
@@ -12,7 +12,7 @@ try:
except ImportError:
REDUCER = False
-from ..version import __pickle__
+from ...version import __pickle__
class Reducer:
diff --git a/src/python/txtai/embeddings/stream.py b/src/python/txtai/embeddings/index/stream.py
similarity index 100%
rename from src/python/txtai/embeddings/stream.py
rename to src/python/txtai/embeddings/index/stream.py
diff --git a/src/python/txtai/embeddings/transform.py b/src/python/txtai/embeddings/index/transform.py
similarity index 89%
rename from src/python/txtai/embeddings/transform.py
rename to src/python/txtai/embeddings/index/transform.py
index 26babe8c..6a08760e 100644
--- a/src/python/txtai/embeddings/transform.py
+++ b/src/python/txtai/embeddings/index/transform.py
@@ -28,10 +28,12 @@ class Transform:
self.action = action
# Alias embeddings attributes
+ self.config = embeddings.config
self.delete = embeddings.delete
self.model = embeddings.model
self.database = embeddings.database
self.graph = embeddings.graph
+ self.indexes = embeddings.indexes
self.scoring = embeddings.scoring if embeddings.issparse() else None
# Get config parameters
@@ -43,6 +45,9 @@ class Transform:
self.text = columns.get("text", "text")
self.object = columns.get("object", "object")
+ # Check if top-level indexing is enabled for this embeddings
+ self.indexing = embeddings.model or embeddings.scoring
+
# List of deleted ids with this action
self.deletes = set()
@@ -117,6 +122,9 @@ class Transform:
for uid, _, _ in self.stream(documents):
ids.append(uid)
+ # Save offset when dense indexing is disabled
+ self.config["offset"] = self.offset
+
return ids
def stream(self, documents):
@@ -142,6 +150,10 @@ class Transform:
# Iterate and process documents stream
for document in documents:
if isinstance(document[1], dict):
+ # Set text field to uid when top-level indexing is disabled and text empty
+ if not self.indexing and not document[1].get(self.text):
+ document[1][self.text] = str(document[0])
+
if self.text in document[1]:
yield (document[0], document[1][self.text], document[2])
offset += 1
@@ -174,7 +186,7 @@ class Transform:
# Delete from embeddings index first (which deletes from underlying indexes and datastores) if this is an upsert
if self.action == Action.UPSERT:
- # Get list of ids not yet seen and delete
+ # Get list of ids not yet seen and deleted
deletes = [uid for uid, _, _ in batch if uid not in self.deletes]
if deletes:
# Execute delete
@@ -187,13 +199,17 @@ class Transform:
if self.database and self.action != Action.REINDEX:
self.database.insert(batch, self.offset)
- # Load batch into graph
- if self.graph:
- self.graph.insert(batch, self.offset)
-
# Load batch into scoring
if self.scoring:
self.scoring.insert(batch, self.offset)
+ # Load batch into subindex documents stream
+ if self.indexes:
+ self.indexes.insert(batch, self.offset)
+
+ # Load batch into graph
+ if self.graph:
+ self.graph.insert(batch, self.offset)
+
# Increment offset
self.offset += offset
diff --git a/src/python/txtai/embeddings/search/__init__.py b/src/python/txtai/embeddings/search/__init__.py
new file mode 100644
index 00000000..d7a15ef0
--- /dev/null
+++ b/src/python/txtai/embeddings/search/__init__.py
@@ -0,0 +1,10 @@
+"""
+Search imports
+"""
+
+from .base import Search
+from .errors import *
+from .explain import Explain
+from .query import Query
+from .scan import Scan
+from .terms import Terms
diff --git a/src/python/txtai/embeddings/search.py b/src/python/txtai/embeddings/search/base.py
similarity index 71%
rename from src/python/txtai/embeddings/search.py
rename to src/python/txtai/embeddings/search/base.py
index c9627061..6063ab4f 100644
--- a/src/python/txtai/embeddings/search.py
+++ b/src/python/txtai/embeddings/search/base.py
@@ -4,6 +4,9 @@ Search module
import logging
+from .errors import IndexNotFoundError
+from .scan import Scan
+
# Logging configuration
logger = logging.getLogger(__name__)
@@ -30,10 +33,11 @@ class Search:
self.batchtransform = embeddings.batchtransform
self.config = embeddings.config
self.database = embeddings.database
+ self.indexes = embeddings.indexes
self.query = embeddings.query
self.scoring = embeddings.scoring if embeddings.issparse() else None
- def __call__(self, queries, limit=None, weights=None):
+ def __call__(self, queries, limit=None, weights=None, index=None):
"""
Executes a batch search for queries. This method will run either an index search or an index + database search
depending on if a database is available.
@@ -42,39 +46,53 @@ class Search:
queries: list of queries
limit: maximum results
weights: hybrid score weights
+ index: index name
Returns:
- list of (id, score) per query for index search, list of dict per query for an index+database search
+ list of (id, score) per query for index search, list of dict per query for an index + database search
"""
# Default input parameters
limit = limit if limit else 3
weights = weights if weights is not None else 0.5
- # Return empty results when indexes are not available
- if not self.ann and not self.scoring:
+ # Return empty results if there is no database and indexes
+ if not self.ann and not self.scoring and not self.indexes and not self.database:
return [[]] * len(queries)
+ # Default index name if only subindexes set
+ if not index and not self.ann and not self.scoring and self.indexes:
+ index = self.indexes.default()
+
+ # Database search
if not self.indexids and self.database:
- return self.dbsearch(queries, limit, weights)
+ return self.dbsearch(queries, limit, weights, index)
- # Default is vector index query (sparse, dense or hybrid)
- return self.search(queries, limit, weights)
+ # Default vector index query (sparse, dense or hybrid)
+ return self.search(queries, limit, weights, index)
- def search(self, queries, limit, weights):
+ def search(self, queries, limit, weights, index):
"""
Executes an index search. When only a sparse index is enabled, this is a a keyword search. When only
a dense index is enabled, this is an ann search. When both are enabled, this is a hybrid search.
+ This method will also query subindexes, if available.
+
Args:
queries: list of queries
limit: maximum results
weights: hybrid score weights
+ index: index name
Returns:
list of (id, score) per query
"""
+ # Run against specified subindex
+ if index:
+ return self.subindex(queries, limit, weights, index)
+
+ # Run against base index
dense = self.dense(queries, limit) if self.ann else None
sparse = self.sparse(queries, limit) if self.scoring else None
@@ -106,9 +124,35 @@ class Search:
return results
+ # Raise an error if when no indexes are available
+ if not sparse and not dense:
+ raise IndexNotFoundError("No indexes available")
+
# Return single query results
return dense if dense else sparse
+ def subindex(self, queries, limit, weights, index):
+ """
+ Executes a subindex search.
+
+ Args:
+ queries: list of queries
+ limit: maximum results
+ weights: hybrid score weights
+ index: index name
+
+ Returns:
+ list of (id, score) per query
+ """
+
+ # Check that index exists
+ if not self.indexes or index not in self.indexes:
+ raise IndexNotFoundError(f"Index '{index}' not found")
+
+ # Run subindex search
+ results = self.indexes[index].batchsearch(queries, limit, weights)
+ return self.resolve(results)
+
def dense(self, queries, limit):
"""
Executes an dense vector search with an approximate nearest neighbor index.
@@ -165,14 +209,15 @@ class Search:
return results
- def dbsearch(self, queries, limit, weights):
+ def dbsearch(self, queries, limit, weights, index):
"""
Executes an index + database search.
Args:
queries: list of queries
limit: maximum results
- weights: hybrid score weights
+ weights: default hybrid score weights
+ index: default index name
Returns:
list of dict per query
@@ -184,20 +229,14 @@ class Search:
# Override limit with query limit, if applicable
limit = max(limit, self.limit(queries))
- # Extract embeddings queries as single batch across all queries
- equeries, candidates = self.extract(queries, limit)
-
- # Bulk index search
- search = self.search([query for _, query in equeries], candidates, weights) if equeries else []
+ # Bulk index scan
+ scan = Scan(self.search, limit, weights, index)(queries)
# Combine index search results with database search results
results = []
for x, query in enumerate(queries):
- # Get search indices for this query within bulk query
- indices = [i for i, (y, _) in enumerate(equeries) if x == y]
-
- # Run the database query
- result = self.database.search(query, [s for i, s in enumerate(search) if i in indices], limit)
+ # Run the database query, get matching bulk searches for current query
+ result = self.database.search(query, [r for y, r in scan if x == y], limit)
results.append(result)
return results
@@ -255,41 +294,3 @@ class Search:
qlimit = l if l and l > qlimit else qlimit
return qlimit
-
- def extract(self, queries, limit):
- """
- Extract embeddings queries text and number of candidates from a list of parsed queries.
-
- The number of candidates are the number of results to bring back from index queries. This is an optional
- second argument to similar() clauses. For a single query filter clause, the default is the query limit.
- With multiple filtering clauses, the default is 10x the query limit. This ensures that limit results
- are still returned with additional filtering after an index query.
-
- Args:
- queries: list of parsed queries
- limit: maximum results
-
- Returns:
- (list of embeddings queries, number of candidates)
- """
-
- # Extract embeddings queries as single batch across all queries
- equeries, candidates = [], 0
- for x, query in enumerate(queries):
- if "similar" in query:
- # Get handle to similar queries
- for params in query["similar"]:
- # Store the query index and similar query argument (first argument)
- equeries.append((x, params[0]))
-
- # Second argument is similar candidate limit
- if len(params) > 1 and params[1].isdigit():
- # Get largest candidate limit across all queries
- candidates = int(params[1]) if int(params[1]) > candidates else candidates
-
- # Default number of candidates, if not specified
- if not candidates:
- multitoken = any(query.get("where") and len(query["where"].split()) > 1 for query in queries)
- candidates = limit * 10 if multitoken else limit
-
- return (equeries, candidates)
diff --git a/src/python/txtai/embeddings/search/errors.py b/src/python/txtai/embeddings/search/errors.py
new file mode 100644
index 00000000..559000f0
--- /dev/null
+++ b/src/python/txtai/embeddings/search/errors.py
@@ -0,0 +1,9 @@
+"""
+Errors module
+"""
+
+
+class IndexNotFoundError(Exception):
+ """
+ Raised when an embeddings query fails to locate an index
+ """
diff --git a/src/python/txtai/embeddings/explain.py b/src/python/txtai/embeddings/search/explain.py
similarity index 100%
rename from src/python/txtai/embeddings/explain.py
rename to src/python/txtai/embeddings/search/explain.py
diff --git a/src/python/txtai/embeddings/query.py b/src/python/txtai/embeddings/search/query.py
similarity index 100%
rename from src/python/txtai/embeddings/query.py
rename to src/python/txtai/embeddings/search/query.py
diff --git a/src/python/txtai/embeddings/search/scan.py b/src/python/txtai/embeddings/search/scan.py
new file mode 100644
index 00000000..076e9fb5
--- /dev/null
+++ b/src/python/txtai/embeddings/search/scan.py
@@ -0,0 +1,168 @@
+"""
+Scan module
+"""
+
+
+class Scan:
+ """
+ Scans indexes for query matches.
+ """
+
+ def __init__(self, search, limit, weights, index):
+ """
+ Creates a new scan instance.
+
+ Args:
+ search: index search function
+ limit: maximum results
+ weights: default hybrid score weights
+ index: default index name
+ """
+
+ # Index search function
+ self.search = search
+
+ # Default query limit
+ self.limit = limit
+
+ # Default number of candidates
+ self.candidates = None
+
+ # Default query weights
+ self.weights = weights
+
+ # Default index
+ self.index = index
+
+ def __call__(self, queries):
+ """
+ Executes a scan for a list of queries.
+
+ Args:
+ queries: list of queries to run
+
+ Returns:
+ list of (id, score) per query
+ """
+
+ # Query results group by unique query clause id
+ results = {}
+
+ # Default number of candidates
+ default = None
+
+ # Group by index and run
+ for index, iqueries in self.parse(queries).items():
+ # Query limit to pass to batch search
+ candidates = [query.candidates for query in iqueries if query.candidates]
+ if not candidates and not default:
+ default = self.default(queries)
+
+ candidates = max(candidates) if candidates else default
+
+ # Query weights to pass to batch search
+ weights = [query.weights for query in iqueries if query.weights is not None]
+ weights = max(weights) if weights else self.weights
+
+ # Index to run query against
+ index = index if index else self.index
+
+ # Run index searches
+ for x, result in enumerate(self.search([query.text for query in iqueries], candidates, weights, index)):
+ # Save query id and results to later join to original query
+ results[iqueries[x].uid] = (iqueries[x].qid, result)
+
+ # Sort by query uid and return results
+ return [result for _, result in sorted(results.items())]
+
+ def parse(self, queries):
+ """
+ Parse index query clauses from a list of parsed queries.
+
+ Args:
+ queries: list of parsed queries
+
+ Returns:
+ index query clauses grouped by index
+ """
+
+ results, uid = {}, 0
+ for x, query in enumerate(queries):
+ if "similar" in query:
+ # Extract similar query clauses
+ for params in query["similar"]:
+ # Parse query clause parameters
+ clause = Clause(uid, x, params)
+
+ # Create clause list for index
+ if clause.index not in results:
+ results[clause.index] = []
+
+ # Add query to index list, increment uid
+ results[clause.index].append(clause)
+ uid += 1
+
+ return results
+
+ def default(self, queries):
+ """
+ Derives the default number of candidates. The number of candidates are the number of results to bring back
+ from index queries. This is an optional argument to similar() clauses.
+
+ For a single query filter clause, the default is the query limit. With multiple filtering clauses, the default is
+ 10x the query limit. This ensures that limit results are still returned with additional filtering after an index query.
+
+ Args:
+ queries: list of queries
+
+ Returns:
+ default candidate list size
+ """
+
+ multitoken = any(query.get("where") and len(query["where"].split()) > 1 for query in queries)
+ return self.limit * 10 if multitoken else self.limit
+
+
+class Clause:
+ """
+ Parses and stores query clause parameters.
+ """
+
+ def __init__(self, uid, qid, params):
+ """
+ Creates a new query clause.
+
+ Args:
+ uid: query clause id
+ qid: query id clause is a part of
+ params: query parameters to parse
+ """
+
+ self.uid, self.qid = uid, qid
+ self.text, self.index = params[0], None
+ self.candidates, self.weights = None, None
+
+ # Parse additional similar clause parameters
+ if len(params) > 1:
+ self.parse(params[1:])
+
+ def parse(self, params):
+ """
+ Parses clause parameters into this instance.
+
+ Args:
+ params: query clause parameters
+ """
+
+ for param in params:
+ if param.isdigit():
+ # Number of query candidates
+ self.candidates = int(param)
+
+ elif param.replace(".", "").isdigit():
+ # Hybrid score weights
+ self.weights = float(param)
+
+ else:
+ # Target index
+ self.index = param
diff --git a/src/python/txtai/embeddings/terms.py b/src/python/txtai/embeddings/search/terms.py
similarity index 100%
rename from src/python/txtai/embeddings/terms.py
rename to src/python/txtai/embeddings/search/terms.py
diff --git a/test/python/testdatabase/testsqlite.py b/test/python/testdatabase/testsqlite.py
index 0abe1211..32f1893e 100644
--- a/test/python/testdatabase/testsqlite.py
+++ b/test/python/testdatabase/testsqlite.py
@@ -8,7 +8,7 @@ import os
import tempfile
import unittest
-from txtai.embeddings import Embeddings
+from txtai.embeddings import Embeddings, IndexNotFoundError
from txtai.database import Database, SQLError
@@ -270,18 +270,25 @@ class TestSQLite(unittest.TestCase):
# Index data with sparse + dense vectors.
embeddings = Embeddings({"path": "sentence-transformers/nli-mpnet-base-v2", "hybrid": True, "content": True})
-
embeddings.index(data)
# Run search
result = embeddings.search("feel good story", 1)[0]
self.assertEqual(result["text"], data[4][1])
- # Index data with sparse + dense vectors. Normalize scores.
- embeddings = Embeddings(
- {"path": "sentence-transformers/nli-mpnet-base-v2", "scoring": {"method": "bm25", "terms": True, "normalize": True}, "content": True}
- )
+ # Generate temp file path
+ index = os.path.join(tempfile.gettempdir(), f"embeddings.{self.backend}.hybrid")
+ # Test load/save
+ embeddings.save(index)
+ embeddings.load(index)
+
+ # Run search
+ result = embeddings.search("feel good story", 1)[0]
+ self.assertEqual(result["text"], data[4][1])
+
+ # Index data with sparse + dense vectors. Normalize scores.
+ embeddings = Embeddings({"path": "sentence-transformers/nli-mpnet-base-v2", "scoring": {"method": "bm25", "terms": True}, "content": True})
embeddings.index(data)
# Run search
@@ -392,13 +399,38 @@ class TestSQLite(unittest.TestCase):
Test keyword only (sparse) search
"""
+ # Build data array
+ data = [(uid, text, None) for uid, text in enumerate(self.data)]
+
# Index data with sparse + dense vectors
embeddings = Embeddings({"keyword": True, "content": True})
- embeddings.index([(uid, text, None) for uid, text in enumerate(self.data)])
+ embeddings.index(data)
# Run search
result = embeddings.search("lottery ticket", 1)[0]
- self.assertEqual(result["text"], self.data[4])
+ self.assertEqual(result["text"], data[4][1])
+
+ # Test count method
+ self.assertEqual(embeddings.count(), len(data))
+
+ # Generate temp file path
+ index = os.path.join(tempfile.gettempdir(), f"embeddings.{self.backend}.keyword")
+
+ # Test load/save
+ embeddings.save(index)
+ embeddings.load(index)
+
+ # Run search
+ result = embeddings.search("lottery ticket", 1)[0]
+ self.assertEqual(result["text"], data[4][1])
+
+ # Update data
+ data[0] = (0, "Feel good story: baby panda born", None)
+ embeddings.upsert([data[0]])
+
+ # Search for best match
+ result = embeddings.search("feel good story", 1)[0]
+ self.assertEqual(result["text"], data[0][1])
def testMultiData(self):
"""
@@ -454,6 +486,23 @@ class TestSQLite(unittest.TestCase):
result = self.embeddings.search("feel good story", 1)[0]
self.assertEqual(result["text"], self.data[4])
+ def testNoIndex(self):
+ """
+ Tests an embeddings instance with no available indexes
+ """
+
+ # Disable top-level indexing
+ embeddings = Embeddings(
+ {
+ "content": True,
+ "defaults": False,
+ }
+ )
+ embeddings.index([(uid, text, None) for uid, text in enumerate(self.data)])
+
+ with self.assertRaises(IndexNotFoundError):
+ embeddings.search("select id, text, score from txtai where similar('feel good story')")
+
def testNotImplemented(self):
"""
Test exceptions for non-implemented methods
@@ -468,6 +517,7 @@ class TestSQLite(unittest.TestCase):
self.assertRaises(NotImplementedError, database.save, None)
self.assertRaises(NotImplementedError, database.close)
self.assertRaises(NotImplementedError, database.ids, None)
+ self.assertRaises(NotImplementedError, database.count)
self.assertRaises(NotImplementedError, database.resolve, None, None)
self.assertRaises(NotImplementedError, database.embed, None, None)
self.assertRaises(NotImplementedError, database.query, None, None)
@@ -585,6 +635,57 @@ class TestSQLite(unittest.TestCase):
with self.assertRaises(SQLError):
self.embeddings.search("select * from txtai where bad,query")
+ def testSubindex(self):
+ """
+ Test subindex
+ """
+
+ # Build data array
+ data = [(uid, text, None) for uid, text in enumerate(self.data)]
+
+ # Disable top-level indexing and create subindex
+ embeddings = Embeddings({"content": True, "defaults": False, "indexes": {"index1": {"path": "sentence-transformers/nli-mpnet-base-v2"}}})
+ embeddings.index(data)
+
+ # Run search
+ result = embeddings.search("feel good story", 1)[0]
+ self.assertEqual(result["text"], data[4][1])
+
+ # Run SQL search
+ result = embeddings.search("select id, text, score from txtai where similar('feel good story', 10, 0.5)")[0]
+ self.assertEqual(result["text"], data[4][1])
+
+ # Test missing index
+ with self.assertRaises(IndexNotFoundError):
+ embeddings.search("select id, text, score from txtai where similar('feel good story', 'notindex')")
+
+ # Generate temp file path
+ index = os.path.join(tempfile.gettempdir(), f"embeddings.{self.backend}.subindex")
+
+ # Test load/save
+ embeddings.save(index)
+ embeddings.load(index)
+
+ # Run search
+ result = embeddings.search("feel good story", 1)[0]
+ self.assertEqual(result["text"], data[4][1])
+
+ # Update data
+ data[0] = (0, "Feel good story: baby panda born", None)
+ embeddings.upsert([data[0]])
+
+ # Search for best match
+ result = embeddings.search("feel good story", 1)[0]
+ self.assertEqual(result["text"], data[0][1])
+
+ # Check missing text is set to id when top-level indexing is disabled
+ embeddings.upsert([(embeddings.count(), {"content": "empty text"}, None)])
+ result = embeddings.search(f"{embeddings.count() - 1}", 1)[0]
+ self.assertEqual(result["text"], str(embeddings.count() - 1))
+
+ # Close embeddings
+ embeddings.close()
+
def testTerms(self):
"""
Test extracting keyword terms from query
@@ -603,6 +704,7 @@ class TestSQLite(unittest.TestCase):
# Reset embeddings for test
self.embeddings.ann = None
+ self.embeddings.database = None
# Create an index for the list of text
self.embeddings.upsert(data)
@@ -613,7 +715,6 @@ class TestSQLite(unittest.TestCase):
# Search for best match
result = self.embeddings.search("feel good story", 1)[0]
-
self.assertEqual(result["text"], data[0][1])
def testUpsertBatch(self):
@@ -627,6 +728,7 @@ class TestSQLite(unittest.TestCase):
# Reset embeddings for test
self.embeddings.ann = None
+ self.embeddings.database = None
# Create an index for the list of text
self.embeddings.upsert(data)
diff --git a/test/python/testembeddings.py b/test/python/testembeddings.py
index 497f3967..ce2bf344 100644
--- a/test/python/testembeddings.py
+++ b/test/python/testembeddings.py
@@ -14,6 +14,7 @@ from txtai.embeddings import Embeddings, Reducer
from txtai.vectors import WordVectors
+# pylint: disable=R0904
class TestEmbeddings(unittest.TestCase):
"""
Embeddings tests.
@@ -184,16 +185,25 @@ class TestEmbeddings(unittest.TestCase):
# Index data with sparse + dense vectors
embeddings = Embeddings({"path": "sentence-transformers/nli-mpnet-base-v2", "hybrid": True})
-
embeddings.index(data)
# Run search
uid = embeddings.search("feel good story", 1)[0][0]
self.assertEqual(uid, 4)
- # Index data with sparse + dense vectors. Normalize scores.
- embeddings = Embeddings({"path": "sentence-transformers/nli-mpnet-base-v2", "scoring": {"method": "bm25", "terms": True, "normalize": True}})
+ # Generate temp file path
+ index = os.path.join(tempfile.gettempdir(), "embeddings.hybrid")
+
+ # Test load/save
+ embeddings.save(index)
+ embeddings.load(index)
+
+ # Run search
+ uid = embeddings.search("feel good story", 1)[0][0]
+ self.assertEqual(uid, 4)
+ # Index data with sparse + dense vectors and unnormalized scores
+ embeddings = Embeddings({"path": "sentence-transformers/nli-mpnet-base-v2", "scoring": {"method": "bm25", "terms": True}})
embeddings.index(data)
# Run search
@@ -225,14 +235,39 @@ class TestEmbeddings(unittest.TestCase):
Test keyword only (sparse) search
"""
+ # Build data array
+ data = [(uid, text, None) for uid, text in enumerate(self.data)]
+
# Index data with sparse + dense vectors
embeddings = Embeddings({"keyword": True})
- embeddings.index([(uid, text, None) for uid, text in enumerate(self.data)])
+ embeddings.index(data)
# Run search
uid = embeddings.search("lottery ticket", 1)[0][0]
self.assertEqual(uid, 4)
+ # Test count method
+ self.assertEqual(embeddings.count(), len(data))
+
+ # Generate temp file path
+ index = os.path.join(tempfile.gettempdir(), "embeddings.keywords")
+
+ # Test load/save
+ embeddings.save(index)
+ embeddings.load(index)
+
+ # Run search
+ uid = embeddings.search("lottery ticket", 1)[0][0]
+ self.assertEqual(uid, 4)
+
+ # Update data
+ data[0] = (0, "Feel good story: baby panda born", None)
+ embeddings.upsert([data[0]])
+
+ # Search for best match
+ uid = embeddings.search("feel good story", 1)[0][0]
+ self.assertEqual(uid, 0)
+
def testNormalize(self):
"""
Test batch normalize and single input normalize are equal
@@ -291,7 +326,7 @@ class TestEmbeddings(unittest.TestCase):
self.embeddings.index([(uid, text, None) for uid, text in enumerate(self.data)])
# Generate temp file path
- index = os.path.join(tempfile.gettempdir(), "embeddings")
+ index = os.path.join(tempfile.gettempdir(), "embeddings.base")
self.embeddings.save(index)
self.embeddings.load(index)
@@ -315,6 +350,49 @@ class TestEmbeddings(unittest.TestCase):
self.assertEqual(uid, 4)
+ def testSubindex(self):
+ """
+ Test subindex
+ """
+
+ # Build data array
+ data = [(uid, text, None) for uid, text in enumerate(self.data)]
+
+ # Disable top-level indexing and create subindex
+ embeddings = Embeddings({"defaults": False, "indexes": {"index1": {"path": "sentence-transformers/nli-mpnet-base-v2"}}})
+ embeddings.index(data)
+
+ # Run search
+ uid = embeddings.search("feel good story", 1)[0][0]
+ self.assertEqual(uid, 4)
+
+ # Generate temp file path
+ index = os.path.join(tempfile.gettempdir(), "embeddings.subindex")
+
+ # Test load/save
+ embeddings.save(index)
+ embeddings.load(index)
+
+ # Run search
+ uid = embeddings.search("feel good story", 1)[0][0]
+ self.assertEqual(uid, 4)
+
+ # Update data
+ data[0] = (0, "Feel good story: baby panda born", None)
+ embeddings.upsert([data[0]])
+
+ # Search for best match
+ uid = embeddings.search("feel good story", 10)[0][0]
+ self.assertEqual(uid, 0)
+
+ # Check missing text is set to id when top-level indexing is disabled
+ embeddings.upsert([(embeddings.count(), {"content": "empty text"}, None)])
+ uid = embeddings.search(f"{embeddings.count() - 1}", 1)[0][0]
+ self.assertEqual(uid, embeddings.count() - 1)
+
+ # Close embeddings
+ embeddings.close()
+
def testUpsert(self):
"""
Test upsert
@@ -325,6 +403,7 @@ class TestEmbeddings(unittest.TestCase):
# Reset embeddings for test
self.embeddings.ann = None
+ del self.embeddings.config["ids"]
# Create an index for the list of text
self.embeddings.upsert(data)
@@ -377,7 +456,7 @@ class TestEmbeddings(unittest.TestCase):
self.assertIsNotNone(embeddings.search("win", 1))
# Generate temp file path
- index = os.path.join(tempfile.gettempdir(), "wembeddings")
+ index = os.path.join(tempfile.gettempdir(), "embeddings.wordvectors")
# Test save/load
embeddings.save(index)
diff --git a/test/python/testgraph.py b/test/python/testgraph.py
index a12f5472..7dbc7033 100644
--- a/test/python/testgraph.py
+++ b/test/python/testgraph.py
@@ -260,6 +260,61 @@ class TestGraph(unittest.TestCase):
graph.addtopics()
self.assertEqual(len(graph.topics), 5)
+ def testSubindex(self):
+ """
+ Test subindex
+ """
+
+ # Build data array
+ data = [(uid, text, None) for uid, text in enumerate(self.data)]
+
+ embeddings = Embeddings(
+ {
+ "content": True,
+ "functions": [{"name": "graph", "function": "indexes.index1.graph.attribute"}],
+ "expressions": [
+ {"name": "category", "expression": "graph(indexid, 'category')"},
+ {"name": "topic", "expression": "graph(indexid, 'topic')"},
+ {"name": "topicrank", "expression": "graph(indexid, 'topicrank')"},
+ ],
+ "indexes": {
+ "index1": {
+ "path": "sentence-transformers/nli-mpnet-base-v2",
+ "graph": {
+ "limit": 5,
+ "minscore": 0.2,
+ "batchsize": 4,
+ "approximate": False,
+ "topics": {"categories": ["News"], "stopwords": ["the"]},
+ },
+ }
+ },
+ }
+ )
+
+ # Create an index for the list of text
+ embeddings.index(data)
+
+ # Test function
+ result = embeddings.search("select id, category, topic, topicrank from txtai where id = 0", 1)[0]
+
+ # Check columns have a value
+ self.assertIsNotNone(result["category"])
+ self.assertIsNotNone(result["topic"])
+ self.assertIsNotNone(result["topicrank"])
+
+ # Update data
+ data[0] = (0, "Feel good story: lottery winner announced", None)
+ embeddings.upsert([data[0]])
+
+ # Test function
+ result = embeddings.search("select id, category, topic, topicrank from txtai where id = 0", 1)[0]
+
+ # Check columns have a value
+ self.assertIsNotNone(result["category"])
+ self.assertIsNotNone(result["topic"])
+ self.assertIsNotNone(result["topicrank"])
+
def testUpsert(self):
"""
Test upsert