💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows
Python agentsaiai-agentsembeddingsinformation-retrievallanguage-modellarge-language-modelsllmnlppythonragretrieval-augmented-generationsearchsearch-enginesemantic-searchsentence-embeddingstransformerstxtaivector-databasevector-search
Hybrid search, closes #509
davidmezzettifebf636de25f
diff --git a/src/python/txtai/app/base.py b/src/python/txtai/app/base.pyindex c19bbe43..c512e87e 100644--- a/src/python/txtai/app/base.py+++ b/src/python/txtai/app/base.py@@ -376,8 +376,8 @@ class Application:if self.embeddings and self.documents:with self.lock:- # Build scoring index if scoring method provided- if self.embeddings.scoring:+ # Build scoring index if term weighting is enabled+ if self.embeddings.isweighted():self.embeddings.score(self.documents)# Build embeddings indexdiff --git a/src/python/txtai/embeddings/base.py b/src/python/txtai/embeddings/base.pyindex 707600f9..19770bb8 100644--- a/src/python/txtai/embeddings/base.py+++ b/src/python/txtai/embeddings/base.py@@ -42,8 +42,7 @@ class Embeddings:# pylint: disable = W0231def __init__(self, config=None, **kwargs):"""- Creates a new embeddings index. Embeddings indexes are thread-safe for read operations but writes must be- synchronized.+ Creates a new embeddings index. Embeddings indexes are thread-safe for read operations but writes must be synchronized.Args:config: embeddings configuration@@ -53,10 +52,10 @@ class Embeddings:# Index configurationself.config = None- # Dimensionality reduction and scoring index - word vectors only- self.reducer, self.scoring = None, None+ # Dimensionality reduction - word vectors only+ self.reducer = None- # Embeddings vector model - transforms data into similarity vectors+ # Dense vector model - transforms data into similarity vectorsself.model = None# Approximate nearest neighbor index@@ -71,6 +70,9 @@ class Embeddings:# Graph networkself.graph = None+ # Sparse vectors+ self.scoring = None+# Query modelself.query = None@@ -85,14 +87,14 @@ class Embeddings:def score(self, documents):"""- Builds a scoring index. Only used by word vectors models.+ Builds a term weighting scoring index. Only used by word vectors models.Args:documents: iterable of (id, data, tags), (id, data) or data"""# Build scoring index for word vectors term weighting- if self.scoring:+ if self.isweighted():self.scoring.index(Stream(self)(documents))def index(self, documents, reindex=False):@@ -104,18 +106,8 @@ class Embeddings:reindex: if this is a reindex operation in which case database creation is skipped, defaults to False"""- # Initialize default parameters, if necessary- self.defaults()-- # Create document database, if necessary- if not reindex:- self.database = self.createdatabase()-- # Reset archive since this is a new index- self.archive = None-- # Create graph, if necessary- self.graph = self.creategraph()+ # Initialize index+ self.initindex(reindex)# Create transform and streamtransform = Transform(self, Action.REINDEX if reindex else Action.INDEX)@@ -124,7 +116,7 @@ class Embeddings:with tempfile.NamedTemporaryFile(mode="wb", suffix=".npy") as buffer:# Load documents into database and transform to vectorsids, dimensions, embeddings = transform(stream(documents), buffer)- if ids:+ if embeddings is not None:# Build LSA model (if enabled). Remove principal components from embeddings.if self.config.get("pca"):self.reducer = Reducer(embeddings, self.config["pca"])@@ -137,19 +129,23 @@ class Embeddings:self.config["dimensions"] = dimensions# Create approximate nearest neighbor index- self.ann = ANNFactory.create(self.config)+ self.ann = self.createann()# Add embeddings to the indexself.ann.index(embeddings)- # Save indexids-ids mapping for indexes with no database, except when this is a reindex- if not reindex and not self.database:- self.config["ids"] = ids+ # Save indexids-ids mapping for indexes with no database, except when this is a reindex+ if ids and not reindex and not self.database:+ self.config["ids"] = ids# Index graph, if necessaryif self.graph:self.graph.index(Search(self, True), self.batchsimilarity)+ # Index scoring, if necessary+ if self.issparse():+ self.scoring.index()+def upsert(self, documents):"""Runs an embeddings upsert operation. If the index exists, new data is@@ -172,7 +168,7 @@ class Embeddings:with tempfile.NamedTemporaryFile(mode="wb", suffix=".npy") as buffer:# Load documents into database and transform to vectorsids, _, embeddings = transform(stream(documents), buffer)- if ids:+ if embeddings is not None:# Remove principal components from embeddings, if necessaryif self.reducer:self.reducer(embeddings)@@ -183,14 +179,18 @@ class Embeddings:# Append embeddings to the indexself.ann.append(embeddings)- # Save indexids-ids mapping for indexes with no database- if not self.database:- self.config["ids"] = self.config["ids"] + ids+ # Save indexids-ids mapping for indexes with no database+ if ids and not self.database:+ self.config["ids"] = self.config["ids"] + ids# Graph upsert, if necessaryif self.graph:self.graph.upsert(Search(self, True), self.batchsimilarity)+ # Scoring upsert, if necessary+ if self.issparse():+ self.scoring.upsert()+def delete(self, ids):"""Deletes from an embeddings index. Returns list of ids deleted.@@ -218,7 +218,7 @@ class Embeddings:# Delete ids from databaseself.database.delete(deletes)- elif self.ann:+ elif self.ann or self.scoring:# Lookup indexids from config for indexes with no databaseindexids = self.config["ids"]@@ -233,13 +233,18 @@ class Embeddings:# Delete indices from ann embeddingsif indices:- # Delete ids from index- self.ann.delete(indices)+ if self.isdense():+ # Delete ids from ANN+ self.ann.delete(indices)# Delete ids from graphif self.graph:self.graph.delete(indices)+ # Delete ids from scoring+ if self.issparse():+ self.scoring.delete(indices)+return deletesdef reindex(self, config, columns=None, function=None):@@ -321,40 +326,40 @@ class Embeddings:number of elements in this embeddings index"""- return self.ann.count() if self.ann else 0+ return self.ann.count() if self.ann else self.scoring.count() if self.scoring else 0- def search(self, query, limit=None):+ def search(self, query, limit=None, weights=None):"""- Finds documents most similar to the input queries. This method will run either an approximate- nearest neighbor (ann) search or an approximate nearest neighbor + database search depending- on if a database is available.+ 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.Args:query: input querylimit: maximum results+ weights: hybrid score weights, if applicableReturns:- list of (id, score) for ann search, list of dict for an ann+database search+ list of (id, score) for index search, list of dict for an index+database search"""- results = self.batchsearch([query], limit)+ results = self.batchsearch([query], limit, weights)return results[0] if results else results- def batchsearch(self, queries, limit=None):+ def batchsearch(self, queries, limit=None, weights=None):"""- Finds documents most similar to the input queries. This method will run either an approximate- nearest neighbor (ann) search or an approximate nearest neighbor + database search depending- on if a database is available.+ 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.Args:queries: input querieslimit: maximum results+ weights: hybrid score weights, if applicableReturns:- list of (id, score) per query for ann search, list of dict per query for an ann+database search+ list of (id, score) per query for index search, list of dict per query for an index+database search"""- return Search(self)(queries, limit if limit else 3)+ return Search(self)(queries, limit, weights)def similarity(self, query, data):"""@@ -474,8 +479,12 @@ class Embeddings:if apath:return os.path.exists(apath)- # Return true if path has a config or config.json file and an embeddings file- return path and (os.path.exists(f"{path}/config") or os.path.exists(f"{path}/config.json")) and os.path.exists(f"{path}/embeddings")+ # Return true if path has a config or config.json file and an embeddings (dense) or scoring (sparse) file+ return (+ path+ and (os.path.exists(f"{path}/config") or os.path.exists(f"{path}/config.json"))+ and (os.path.exists(f"{path}/embeddings") or os.path.exists(f"{path}/scoring"))+ )def load(self, path=None, cloud=None, **kwargs):"""@@ -500,26 +509,16 @@ class Embeddings:# Load index configurationself.config = self.loadconfig(path)- # Approximate nearest neighbor index - stores embeddings vectors- self.ann = ANNFactory.create(self.config)- self.ann.load(f"{path}/embeddings")+ # Approximate nearest neighbor index - stores dense vectors+ self.ann = self.createann()+ if self.ann:+ self.ann.load(f"{path}/embeddings")# Dimensionality reduction model - word vectors onlyif self.config.get("pca"):self.reducer = Reducer()self.reducer.load(f"{path}/lsa")- # Embedding scoring index - word vectors only- if self.config.get("scoring"):- self.scoring = ScoringFactory.create(self.config["scoring"])- self.scoring.load(f"{path}/scoring")-- # Sentence vectors model - transforms data to embeddings vectors- self.model = self.loadvectors()-- # Query model- self.query = self.loadquery()-# Document database - stores document contentself.database = self.createdatabase()if self.database:@@ -530,6 +529,17 @@ class Embeddings: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")++ # Dense vectors - transforms data to embeddings vectors+ self.model = self.loadvectors()++ # Query model+ self.query = self.loadquery()+def save(self, path, cloud=None, **kwargs):"""Saves an index in a directory at path unless path ends with tar.gz, tar.bz2, tar.xz or zip.@@ -558,16 +568,13 @@ class Embeddings:self.saveconfig(path)# Save approximate nearest neighbor index- self.ann.save(f"{path}/embeddings")+ if self.ann:+ self.ann.save(f"{path}/embeddings")# Save dimensionality reduction model (word vectors only)if self.reducer:self.reducer.save(f"{path}/lsa")- # Save embedding scoring index (word vectors only)- if self.scoring:- self.scoring.save(f"{path}/scoring")-# Save document databaseif self.database:self.database.save(f"{path}/documents")@@ -576,6 +583,10 @@ class Embeddings:if self.graph:self.graph.save(f"{path}/graph")+ # Save scoring index+ if self.scoring:+ self.scoring.save(f"{path}/scoring")+# If this is an archive, save itif apath:self.archive.save(apath)@@ -590,14 +601,19 @@ class Embeddings:Closes this embeddings index and frees all resources."""- self.config, self.reducer, self.scoring, self.model = None, None, None, None- self.ann, self.graph, self.query, self.archive = None, None, None, None+ self.config, self.reducer, self.query, self.model = None, None, None, None+ self.ann, self.graph, self.archive = None, None, None# Close database connection if openif self.database:self.database.close()self.database, self.functions = None, None+ # Close scoring instance if open+ if self.scoring:+ self.scoring.close()+ self.scoring = None+def info(self):"""Prints the current embeddings index configuration.@@ -613,6 +629,36 @@ class Embeddings:# Print configurationprint(json.dumps(config, sort_keys=True, default=str, indent=2))+ def issparse(self):+ """+ Checks if this instance has an associated scoring instance with term indexing enabled.++ Returns:+ True if term index is enabled, False otherwise+ """++ return self.scoring and self.scoring.hasterms()++ def isdense(self):+ """+ Checks if this instance has an associated ANN instance.++ Returns:+ True if this instance has an associated ANN, False otherwise+ """++ return self.ann is not None++ def isweighted(self):+ """+ Checks if this instance has an associated scoring instance with term weighting enabled.++ Returns:+ True if term weighting is enabled, False otherwise+ """++ return self.scoring and not self.scoring.hasterms()+def configure(self, config):"""Sets the configuration for this embeddings index and loads config-driven models.@@ -624,21 +670,45 @@ class Embeddings:# Configurationself.config = config- if self.config and self.config.get("method") != "transformers":- # Dimensionality reduction model- self.reducer = None+ # Dimensionality reduction model+ self.reducer = None- # Embedding scoring method - weighs each word in a sentence- self.scoring = ScoringFactory.create(self.config["scoring"]) if self.config and self.config.get("scoring") else None- else:- self.reducer, self.scoring = None, None+ # Create scoring instance for word vectors term weighting+ scoring = self.config.get("scoring") if self.config else None+ self.scoring = self.createscoring() if scoring and (not isinstance(scoring, dict) or not scoring.get("terms")) else None- # Sentence vectors model - transforms data to embeddings vectors+ # Dense vectors - transforms data to embeddings vectorsself.model = self.loadvectors() if self.config else None# Query modelself.query = self.loadquery() if self.config else None+ def initindex(self, reindex):+ """+ Initialize new index.++ Args:+ reindex: if this is a reindex operation in which case database creation is skipped, defaults to False+ """++ # Initialize default parameters, if necessary+ self.defaults()++ # Create document database, if necessary+ if not reindex:+ self.database = self.createdatabase()++ # 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()+def defaults(self):"""Apply default parameters to current configuration.@@ -649,11 +719,15 @@ class Embeddings:self.config = self.config if self.config else {}- # Add default path if configuration available- if not self.model:+ # 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}++ # Add default path if configuration available and this isn't a keyword index+ if not self.model and not self.config.get("keyword"):self.config["path"] = "sentence-transformers/all-MiniLM-L6-v2"- # Configure instance+ # Load dense vectors modelself.model = self.loadvectors()def loadconfig(self, path):@@ -772,6 +846,16 @@ class Embeddings:# Create cloud instance from config and returnreturn CloudFactory.create(config) if config else None+ def createann(self):+ """+ Creates an ANN from config.++ Returns:+ new ANN, if enabled in config+ """++ return ANNFactory.create(self.config) if self.config.get("path") or not self.config.get("keyword") else None+def createdatabase(self):"""Creates a database from config. This method will also close any existing database connection.@@ -804,6 +888,20 @@ class Embeddings:return GraphFactory.create(self.config["graph"]) if "graph" in self.config else None+ def createscoring(self):+ """+ Creates a scoring from config.++ Returns:+ new scoring, if enabled in config+ """++ # Free existing resources+ if self.scoring:+ self.scoring.close()++ return ScoringFactory.create(self.config["scoring"]) if "scoring" in self.config else None+def normalize(self, embeddings):"""Normalizes embeddings using L2 normalization. Operation applied directly on array.diff --git a/src/python/txtai/embeddings/explain.py b/src/python/txtai/embeddings/explain.pyindex 32f2b424..38cba1c2 100644--- a/src/python/txtai/embeddings/explain.py+++ b/src/python/txtai/embeddings/explain.py@@ -20,10 +20,10 @@ class Explain:"""self.embeddings = embeddings- self.content = self.embeddings.config.get("content")+ self.content = embeddings.config.get("content")# Alias embeddings attributes- self.database = self.embeddings.database+ self.database = embeddings.databasedef __call__(self, queries, texts, limit):"""diff --git a/src/python/txtai/embeddings/search.py b/src/python/txtai/embeddings/search.pyindex 456f80a8..c9627061 100644--- a/src/python/txtai/embeddings/search.py+++ b/src/python/txtai/embeddings/search.py@@ -10,7 +10,7 @@ logger = logging.getLogger(__name__)class Search:"""- Executes a batch search action. A search can be both approximate nearest neighbor and/or database driven.+ Executes a batch search action. A search can be both index and/or database driven."""def __init__(self, embeddings, indexids=False):@@ -26,38 +26,92 @@ class Search:self.indexids = indexids# Alias embeddings attributes- self.config = embeddings.configself.ann = embeddings.ann- self.database = embeddings.databaseself.batchtransform = embeddings.batchtransform+ self.config = embeddings.config+ self.database = embeddings.databaseself.query = embeddings.query+ self.scoring = embeddings.scoring if embeddings.issparse() else None- def __call__(self, queries, limit):+ def __call__(self, queries, limit=None, weights=None):"""- Executes a batch search for queries. This method will run either an approximate nearest neighbor (ann) search- or an approximate nearest neighbor + database search depending on if a database is available.+ 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.Args:queries: list of querieslimit: maximum results+ weights: hybrid score weightsReturns:- list of (id, score) per query for ann search, list of dict per query for an ann+database search+ list of (id, score) per query for index search, list of dict per query for an index+database search"""- # Return empty results if ANN is not set- if not self.ann:+ # 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 [[]] * len(queries)if not self.indexids and self.database:- return self.dbsearch(queries, limit)+ return self.dbsearch(queries, limit, weights)- # Default: execute an approximate nearest neighbor search- return self.search(queries, limit)+ # Default is vector index query (sparse, dense or hybrid)+ return self.search(queries, limit, weights)- def search(self, queries, limit):+ def search(self, queries, limit, weights):"""- Executes an approximate nearest neighbor search.+ 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.++ Args:+ queries: list of queries+ limit: maximum results+ weights: hybrid score weights++ Returns:+ list of (id, score) per query+ """++ dense = self.dense(queries, limit) if self.ann else None+ sparse = self.sparse(queries, limit) if self.scoring else None++ # Combine scores together+ if dense and sparse:+ # Create weights array if single number passed+ if isinstance(weights, (int, float)):+ weights = [weights, 1 - weights]++ # Create weighted scores+ results = []+ for vectors in zip(dense, sparse):+ uids = {}+ for v, scores in enumerate(vectors):+ for r, (uid, score) in enumerate(scores if weights[v] > 0 else []):+ # Initialize score+ if uid not in uids:+ uids[uid] = 0.0++ # Create hybrid score+ # - Convex Combination when sparse scores are normalized+ # - Reciprocal Rank Fusion (RRF) when sparse scores aren't normalized+ if self.scoring.isnormalized():+ uids[uid] += score * weights[v]+ else:+ uids[uid] += (1.0 / (r + 1)) * weights[v]++ results.append(sorted(uids.items(), key=lambda x: x[1], reverse=True)[:limit])++ return results++ # Return single query results+ return dense if dense else sparse++ def dense(self, queries, limit):+ """+ Executes an dense vector search with an approximate nearest neighbor index.Args:queries: list of queries@@ -76,6 +130,34 @@ class Search:# Require scores to be greater than 0results = [[(i, score) for i, score in r if score > 0] for r in results]+ return self.resolve(results)++ def sparse(self, queries, limit):+ """+ Executes a sparse vector search with a term frequency sparse array.++ Args:+ queries: list of queries+ limit: maximum results++ Returns:+ list of (id, score) per query+ """++ # Search term frequency sparse index+ return self.resolve(self.scoring.batchsearch(queries, limit))++ def resolve(self, results):+ """+ Resolves index ids. This is only executed when content is disabled.++ Args:+ results: results++ Returns:+ results with resolved ids+ """+# Map indexids to ids if "ids" availableif not self.indexids and "ids" in self.config:lookup = self.config["ids"]@@ -83,13 +165,14 @@ class Search:return results- def dbsearch(self, queries, limit):+ def dbsearch(self, queries, limit, weights):"""- Executes an approximate nearest neighbor + database search.+ Executes an index + database search.Args:queries: list of querieslimit: maximum results+ weights: hybrid score weightsReturns:list of dict per query@@ -104,10 +187,10 @@ class Search:# Extract embeddings queries as single batch across all queriesequeries, candidates = self.extract(queries, limit)- # Bulk approximate nearest neighbor search- search = self.search([query for _, query in equeries], candidates) if equeries else []+ # Bulk index search+ search = self.search([query for _, query in equeries], candidates, weights) if equeries else []- # Combine approximate nearest neighbor search results with database search results+ # Combine index search results with database search resultsresults = []for x, query in enumerate(queries):# Get search indices for this query within bulk query@@ -177,10 +260,10 @@ class Search:"""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 ANN queries. This is an optional+ The number of candidates are the number of results to bring back from index queries. This is an optionalsecond 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 ANN query.+ are still returned with additional filtering after an index query.Args:queries: list of parsed queriesdiff --git a/src/python/txtai/embeddings/stream.py b/src/python/txtai/embeddings/stream.pyindex 6db91d13..9cc641ae 100644--- a/src/python/txtai/embeddings/stream.py+++ b/src/python/txtai/embeddings/stream.py@@ -24,14 +24,14 @@ class Stream:self.action = action# Alias embeddings attributes- self.config = self.embeddings.config+ self.config = embeddings.config# Get config parameters- self.offset = self.config.get("offset", 0) if self.action == Action.UPSERT else 0+ self.offset = self.config.get("offset", 0) if action == Action.UPSERT else 0autoid = self.config.get("autoid", self.offset)# Create autoid generator, reset int sequence if this isn't an UPSERT- autoid = 0 if isinstance(autoid, int) and self.action != Action.UPSERT else autoid+ autoid = 0 if isinstance(autoid, int) and action != Action.UPSERT else autoidself.autoid = AutoId(autoid)def __call__(self, documents):diff --git a/src/python/txtai/embeddings/transform.py b/src/python/txtai/embeddings/transform.pyindex 3702ddd2..f8c7bd0b 100644--- a/src/python/txtai/embeddings/transform.py+++ b/src/python/txtai/embeddings/transform.py@@ -12,7 +12,7 @@ from .action import Actionclass Transform:"""- Executes a transform. Processes a stream of documents, loads batches into a database and vectorizes documents.+ Executes a transform. Processes a stream of documents, loads batches into enabled data stores and vectorizes documents."""def __init__(self, embeddings, action):@@ -28,14 +28,15 @@ class Transform:self.action = action# Alias embeddings attributes- self.delete = self.embeddings.delete- self.model = self.embeddings.model- self.database = self.embeddings.database- self.graph = self.embeddings.graph+ self.delete = embeddings.delete+ self.model = embeddings.model+ self.database = embeddings.database+ self.graph = embeddings.graph+ self.scoring = embeddings.scoring if embeddings.issparse() else None# Get config parameters- self.offset = self.embeddings.config.get("offset", 0) if self.action == Action.UPSERT else 0- self.batch = self.embeddings.config.get("batch", 1024)+ self.offset = embeddings.config.get("offset", 0) if action == Action.UPSERT else 0+ self.batch = embeddings.config.get("batch", 1024)# List of deleted ids with this actionself.deletes = set()@@ -44,7 +45,7 @@ class Transform:"""Processes an iterable collection of documents, handles any iterable including generators.- This method loads a stream of documents into a database (if applicable) and vectorizes documents into an embeddings array.+ This method loads a stream of documents into enabled data stores and vectorizes documents into an embeddings array.Args:documents: iterable of (id, data, tags)@@ -54,7 +55,29 @@ class Transform:(document ids, dimensions, embeddings)"""- # Transform documents to vectors and load into database+ # Return parameters+ ids, dimensions, embeddings = None, None, None++ if self.model:+ ids, dimensions, embeddings = self.vectors(documents, buffer)+ else:+ ids = self.ids(documents)++ return (ids, dimensions, embeddings)++ def vectors(self, documents, buffer):+ """+ Runs a vectors transform operation when dense indexing is enabled.++ Args:+ documents: iterable of (id, data, tags)+ buffer: file path used for memmap buffer++ Returns:+ (document ids, dimensions, embeddings)+ """++ # Consume stream and transform documents to vectorsids, dimensions, batches, stream = self.model.index(self.stream(documents), self.batch)# Check that embeddings are available and load as a memmap@@ -73,18 +96,36 @@ class Transform:return (ids, dimensions, embeddings)+ def ids(self, documents):+ """+ Runs an ids transform operation when dense indexing is disabled.++ Args:+ documents: iterable of (id, data, tags)++ Returns:+ document ids+ """++ # Consume stream and build extract ids+ ids = []+ for uid, _, _ in self.stream(documents):+ ids.append(uid)++ return ids+def stream(self, documents):"""This method does two things:1. Filter and yield data to vectorize- 2. Batch and load original documents into a database (if applicable)+ 2. Batch and load original documents into enabled data stores (database, graph, scoring)Documents are yielded for vectorization if one of the following is True:- dict with the field "text" or "object"- not a dict- Otherwise, documents are only batched and inserted into a database+ Otherwise, documents are only batched and inserted into data storesArgs:documents: iterable collection (id, data, tags)@@ -119,14 +160,14 @@ class Transform:def load(self, batch, offset):"""Loads a document batch. This method deletes existing ids from an embeddings index and- load into a database, if applicable.+ loads into enabled data stores (database, graph, scoring).Args:batch: list of (id, data, tags)offset: index offset for batch"""- # Delete from embeddings index first (which deletes from underlying ANN index and database) if this is an upsert+ # Delete from embeddings index first (which deletes from underlying indexes and datastores) if this is an upsertif self.action == Action.UPSERT:# Get list of ids not yet seen and deletedeletes = [uid for uid, _, _ in batch if uid not in self.deletes]@@ -145,5 +186,9 @@ class Transform:if self.graph:self.graph.insert(batch, self.offset)+ # Load batch into scoring+ if self.scoring:+ self.scoring.insert(batch, self.offset)+# Increment offsetself.offset += offsetdiff --git a/src/python/txtai/scoring/base.py b/src/python/txtai/scoring/base.pyindex 83a44d8e..d6659aa9 100644--- a/src/python/txtai/scoring/base.py+++ b/src/python/txtai/scoring/base.py@@ -62,6 +62,7 @@ class Scoring:# Normalize scoresself.normalize = self.config.get("normalize")+ self.avgscore = Nonedef insert(self, documents, index=None):"""@@ -72,30 +73,34 @@ class Scoring:index: indexid offset"""- # Calculate word frequency, total tokens and total documents- for uid, data, tags in documents:- # If index is passed, use indexid, otherwise use id- uid = index if index is not None else uid+ # Insert documents, calculate word frequency, total tokens and total documents+ for uid, document, tags in documents:+ # Extract text, if necessary+ if isinstance(document, dict):+ document = document.get("text", document.get("object"))- if self.documents is not None:- self.documents[uid] = data+ if document is not None:+ # If index is passed, use indexid, otherwise use id+ uid = index if index is not None else uid- # Extract text, if necessary- if isinstance(data, dict):- data = data.get("text")+ # Add entry to index if the data type is accepted+ if isinstance(document, (str, list)):+ # Store content+ if self.documents is not None:+ self.documents[uid] = document- # Convert to tokens, if necessary- tokens = self.tokenize(data) if isinstance(data, str) else data+ # Convert to tokens, if necessary+ tokens = self.tokenize(document) if isinstance(document, str) else document- # Add tokens for id to term index- if self.terms is not None:- self.terms.insert(uid, tokens)+ # Add tokens for id to term index+ if self.terms is not None:+ self.terms.insert(uid, tokens)- # Add tokens and tags to stats- self.addstats(tokens, tags)+ # Add tokens and tags to stats+ self.addstats(tokens, tags)- # Increment index- index = index + 1 if index is not None else None+ # Increment index+ index = index + 1 if index is not None else Nonedef delete(self, ids):"""@@ -145,6 +150,9 @@ class Scoring:# Average IDF score per tokenself.avgidf = np.mean(idfs)+ # Calculate average score across index+ self.avgscore = self.score(self.avgfreq, self.avgidf, self.avgdl)+# Filter for tags that appear in at least 1% of the documentsself.tags = {tag: number for tag, number in self.tags.items() if number >= self.total * 0.005}@@ -164,7 +172,7 @@ class Scoring:def weights(self, tokens):"""- Builds weight vector for each token in the input token.+ Builds a weights vector for each token in input tokens.Args:tokens: input tokens@@ -218,9 +226,10 @@ class Scoring:scores = self.terms.search(query, limit)# Normalize scores, if enabled- if self.normalize:- # Calculate max score = 4 * average score- maxscore = 4 * self.score(self.avgfreq, self.avgidf, self.avgdl)+ if self.normalize and scores:+ # Calculate max score = best score for this query + average index score+ # Limit max to 6 * average index score+ maxscore = min(scores[0][1] + self.avgscore, 6 * self.avgscore)# Normalize scores between 0 - 1 using maxscorescores = [(x, min(score / maxscore, 1.0)) for x, score in scores]@@ -295,6 +304,34 @@ class Scoring:if self.terms:self.terms.save(path + ".terms")+ def close(self):+ """+ Close and free resources used by this instance.+ """++ if self.terms:+ self.terms.close()++ def hasterms(self):+ """+ Check if this scoring instance has an associated terms index.++ Returns:+ True if this scoring instance has an associated terms index.+ """++ return self.terms is not None++ def isnormalized(self):+ """+ Check if this scoring instance returns normalized scores.++ Returns:+ True if normalize is enabled, False otherwise+ """++ return self.normalize+def computefreq(self, tokens):"""Computes token frequency. Used for token weighting.@@ -407,14 +444,6 @@ class Scoring:"""if self.documents:- results = []- for x, score in scores:- data = self.documents[x]- if isinstance(data, dict):- results.append({"id": x, "text": data.get("text"), "score": score, "data": data})- else:- results.append({"id": x, "text": data, "score": score})-- return results+ return [{"id": x, "text": self.documents[x], "score": score} for x, score in scores]return scoresdiff --git a/src/python/txtai/scoring/terms.py b/src/python/txtai/scoring/terms.pyindex 8b8a87d0..cd7f7b96 100644--- a/src/python/txtai/scoring/terms.py+++ b/src/python/txtai/scoring/terms.py@@ -276,6 +276,15 @@ class Terms:else:self.copy(path).close()+ def close(self):+ """+ Close and free resources used by this instance.+ """++ # Close connection+ if self.connection:+ self.connection.close()+def initialize(self):"""Creates connection and initial database schema if no connection exists.@@ -440,7 +449,7 @@ class Terms:matches = matches[np.argsort(-scores[matches])]# Combine ids with scores. Require score > 0.- return [(self.ids[x], scores[x]) for x in matches[:limit] if scores[x] > 0]+ return [(self.ids[x], float(scores[x])) for x in matches[:limit] if scores[x] > 0]def merge(self, scores, matches, hasscores, terms):"""diff --git a/test/python/testdatabase/testsqlite.py b/test/python/testdatabase/testsqlite.pyindex e73159d2..a3af60b4 100644--- a/test/python/testdatabase/testsqlite.py+++ b/test/python/testdatabase/testsqlite.py@@ -100,7 +100,9 @@ class TestSQLite(unittest.TestCase):# Create index twice to test open/close and ensure resources are freedfor _ in range(2):- embeddings = Embeddings({"path": "sentence-transformers/nli-mpnet-base-v2", "content": self.backend})+ embeddings = Embeddings(+ {"path": "sentence-transformers/nli-mpnet-base-v2", "scoring": {"method": "bm25", "terms": True}, "content": self.backend}+ )# Add record to indexembeddings.index([(0, "Close test", None)])@@ -245,6 +247,41 @@ class TestSQLite(unittest.TestCase):self.assertEqual(result["text"], self.data[4])+ def testHybrid(self):+ """+ Test hybrid search+ """++ # Build data array+ data = [(uid, text, None) for uid, text in enumerate(self.data)]++ # 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}+ )++ embeddings.index(data)++ # Run search+ result = embeddings.search("feel good story", 1)[0]+ self.assertEqual(result["text"], data[4][1])++ # Test upsert+ data[0] = (0, "Feel good story: baby panda born", None)+ embeddings.upsert([data[0]])++ result = embeddings.search("feel good story", 1)[0]+ self.assertEqual(result["text"], data[0][1])+def testIndex(self):"""Test index@@ -337,6 +374,19 @@ class TestSQLite(unittest.TestCase):embeddings.load(index)self.assertEqual(embeddings.count(), 6)+ def testKeyword(self):+ """+ Test keyword only (sparse) search+ """++ # Index data with sparse + dense vectors+ embeddings = Embeddings({"keyword": True, "content": True})+ embeddings.index([(uid, text, None) for uid, text in enumerate(self.data)])++ # Run search+ result = embeddings.search("lottery ticket", 1)[0]+ self.assertEqual(result["text"], self.data[4])+def testMultiData(self):"""Test indexing with multiple data types (text, documents)diff --git a/test/python/testembeddings.py b/test/python/testembeddings.pyindex 064faec5..e1763546 100644--- a/test/python/testembeddings.py+++ b/test/python/testembeddings.py@@ -161,6 +161,39 @@ class TestEmbeddings(unittest.TestCase):uid = embeddings.search(data[4], 1)[0][0]self.assertEqual(uid, 4)+ def testHybrid(self):+ """+ Test hybrid search+ """++ # Build data array+ data = [(uid, text, None) for uid, text in enumerate(self.data)]++ # 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}})++ embeddings.index(data)++ # Run search+ uid = embeddings.search("feel good story", 1)[0][0]+ self.assertEqual(uid, 4)++ # Test upsert+ data[0] = (0, "Feel good story: baby panda born", None)+ embeddings.upsert([data[0]])++ uid = embeddings.search("feel good story", 1)[0][0]+ self.assertEqual(uid, 0)+def testIndex(self):"""Test index@@ -174,6 +207,19 @@ class TestEmbeddings(unittest.TestCase):self.assertEqual(uid, 4)+ def testKeyword(self):+ """+ Test keyword only (sparse) search+ """++ # Index data with sparse + dense vectors+ embeddings = Embeddings({"keyword": True})+ embeddings.index([(uid, text, None) for uid, text in enumerate(self.data)])++ # Run search+ uid = embeddings.search("lottery ticket", 1)[0][0]+ self.assertEqual(uid, 4)+def testNormalize(self):"""Test batch normalize and single input normalize are equaldiff --git a/test/python/testscoring.py b/test/python/testscoring.pyindex 668cf5e3..54c46083 100644--- a/test/python/testscoring.py+++ b/test/python/testscoring.py@@ -80,6 +80,7 @@ class TestScoring(unittest.TestCase):self.normalize(config)self.content(config)self.empty(config)+ self.copy(config)self.settings(config)def index(self, config, data=None):@@ -147,10 +148,6 @@ class TestScoring(unittest.TestCase):index = os.path.join(tempfile.gettempdir(), "scoring")os.makedirs(index, exist_ok=True)- # Create file to test replacing existing file- with open(f"{index}.terms", "w", encoding="utf-8") as f:- f.write("TEST")-# Save scoring instancescoring.save(f"{index}/{name}")@@ -298,6 +295,28 @@ class TestScoring(unittest.TestCase):# Assert index call returns and index has a count of 0self.assertEqual(scoring.total, 0)+ def copy(self, config):+ """+ Test scoring index copy method.+ """++ # Create scoring instance+ scoring = ScoringFactory.create({**config, **{"terms": True}})+ scoring.index(self.data)++ # Generate temp file path+ index = os.path.join(tempfile.gettempdir(), "scoring")+ os.makedirs(index, exist_ok=True)++ # Create file to test replacing existing file+ path = f"{index}/scoring.{config['method']}.copy"+ with open(f"{index}.terms", "w", encoding="utf-8") as f:+ f.write("TEST")++ # Save scoring instance+ scoring.save(path)+ self.assertTrue(os.path.exists(path))+@patch("sys.byteorder", "big")def settings(self, config):"""