Skip to content

armgit / txtai

Public Imported from GitHub
0

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

Better BM25, closes #508

davidmezzetti75b4a8e7a25c
diff --git a/src/python/txtai/scoring/__init__.py b/src/python/txtai/scoring/__init__.py
index c4850c9b..51a62eaa 100644
--- a/src/python/txtai/scoring/__init__.py
+++ b/src/python/txtai/scoring/__init__.py
@@ -6,3 +6,4 @@ from .base import Scoring
from .bm25 import BM25
from .factory import ScoringFactory
from .sif import SIF
+from .terms import Terms
diff --git a/src/python/txtai/scoring/base.py b/src/python/txtai/scoring/base.py
index 05af3493..83a44d8e 100644
--- a/src/python/txtai/scoring/base.py
+++ b/src/python/txtai/scoring/base.py
@@ -3,14 +3,20 @@ Scoring module
"""
import math
+import os
import pickle
from collections import Counter
+from multiprocessing.pool import ThreadPool
+
+import numpy as np
from .. import __pickle__
from ..pipeline import Tokenizer
+from .terms import Terms
+
class Scoring:
"""
@@ -33,13 +39,6 @@ class Scoring:
self.tokens = 0
self.avgdl = 0
- # Document data
- self.documents = {} if self.config.get("content") else None
- self.docterms = {} if self.config.get("terms") else None
-
- # Normalize scores
- self.normalize = self.config.get("normalize")
-
# Word frequency
self.docfreq = Counter()
self.wordfreq = Counter()
@@ -52,57 +51,32 @@ class Scoring:
# Tag boosting
self.tags = Counter()
- def index(self, documents):
- """
- Indexes a collection of documents using a scoring method.
-
- Args:
- documents: list of (id, dict|text|tokens, tags)
- """
-
- # Parse documents
- tokenlists = self.parse(documents)
-
- # Build index if tokens parsed
- if self.wordfreq:
- # Calculate total token frequency
- self.tokens = sum(self.wordfreq.values())
-
- # Calculate average frequency per token
- self.avgfreq = self.tokens / len(self.wordfreq.values())
-
- # Calculate average document length in tokens
- self.avgdl = self.tokens / self.total
+ # Tokenizer, lazily loaded as needed
+ self.tokenizer = None
- # Compute IDF scores
- for word, freq in self.docfreq.items():
- self.idf[word] = self.computeidf(freq)
-
- # Average IDF score per token
- self.avgidf = sum(self.idf.values()) / len(self.idf)
+ # Term index
+ self.terms = Terms(self.config["terms"], self.score, self.idf) if self.config.get("terms") else None
- # Filter for tags that appear in at least 1% of the documents
- self.tags = {tag: number for tag, number in self.tags.items() if number >= self.total * 0.005}
+ # Document data
+ self.documents = {} if self.config.get("content") else None
- # Process document terms, if necessary
- self.terms(tokenlists)
+ # Normalize scores
+ self.normalize = self.config.get("normalize")
- def parse(self, documents):
+ def insert(self, documents, index=None):
"""
- Parses document stats, word frequencies and data from documents.
+ Inserts documents into the scoring index.
Args:
- docments: list of (id, dict|text|tokens, tags)
-
- Returns:
- tokenlists: list of parsed documents when term parsing is enabled, empty dict otherwise
+ documents: list of (id, dict|text|tokens, tags)
+ index: indexid offset
"""
- # Store tokenlists when term indexing enabled
- tokenlists = {}
-
# 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
+
if self.documents is not None:
self.documents[uid] = data
@@ -111,44 +85,82 @@ class Scoring:
data = data.get("text")
# Convert to tokens, if necessary
- tokens = Tokenizer.tokenize(data) if isinstance(data, str) else data
+ tokens = self.tokenize(data) if isinstance(data, str) else data
- # Save tokens for term indexing
- if self.docterms is not None:
- tokenlists[uid] = tokens
+ # Add tokens for id to term index
+ if self.terms is not None:
+ self.terms.insert(uid, tokens)
- # Total number of times token appears, count all tokens
- self.wordfreq.update(tokens)
+ # Add tokens and tags to stats
+ self.addstats(tokens, tags)
- # Total number of documents a token is in, count unique tokens
- self.docfreq.update(set(tokens))
+ # Increment index
+ index = index + 1 if index is not None else None
- # Get list of unique tags
- if tags:
- self.tags.update(tags.split())
+ def delete(self, ids):
+ """
+ Deletes documents from scoring index.
+
+ Args:
+ ids: list of ids to delete
+ """
- # Total document count
- self.total += 1
+ # Delete from terms index
+ if self.terms:
+ self.terms.delete(ids)
- return tokenlists
+ # Delete content
+ if self.documents:
+ for uid in ids:
+ self.documents.pop(uid)
- def terms(self, tokenlist):
+ def index(self, documents=None):
"""
- Add term weights for each tokenized document in tokenlist.
+ Indexes a collection of documents using a scoring method.
Args:
- tokenlist: list of tokenized documents
+ documents: list of (id, dict|text|tokens, tags)
"""
- for uid in tokenlist:
- tokens = tokenlist[uid]
- weights = self.weights(tokens)
+ # Insert documents
+ if documents:
+ self.insert(documents)
- for x, token in enumerate(tokens):
- if token not in self.docterms:
- self.docterms[token] = {}
+ # Build index if tokens parsed
+ if self.wordfreq:
+ # Calculate total token frequency
+ self.tokens = sum(self.wordfreq.values())
- self.docterms[token][uid] = weights[x]
+ # Calculate average frequency per token
+ self.avgfreq = self.tokens / len(self.wordfreq.values())
+
+ # Calculate average document length in tokens
+ self.avgdl = self.tokens / self.total
+
+ # Compute IDF scores
+ idfs = self.computeidf(np.array(list(self.docfreq.values())))
+ for x, word in enumerate(self.docfreq):
+ self.idf[word] = idfs[x]
+
+ # Average IDF score per token
+ self.avgidf = np.mean(idfs)
+
+ # Filter for tags that appear in at least 1% of the documents
+ self.tags = {tag: number for tag, number in self.tags.items() if number >= self.total * 0.005}
+
+ # Index terms, if available
+ if self.terms:
+ self.terms.index()
+
+ def upsert(self, documents=None):
+ """
+ Convience method for API clarity. Calls index method.
+
+ Args:
+ documents: list of (id, dict|text|tokens, tags)
+ """
+
+ self.index(documents)
def weights(self, tokens):
"""
@@ -161,21 +173,18 @@ class Scoring:
list of weights for each token
"""
- # Weights array
- weights = []
-
# Document length
length = len(tokens)
# Calculate token counts
freq = self.computefreq(tokens)
+ freq = np.array([freq[token] for token in tokens])
- for token in tokens:
- # Lookup idf score
- idf = self.idf[token] if token in self.idf else self.avgidf
+ # Get idf scores
+ idf = np.array([self.idf[token] if token in self.idf else self.avgidf for token in tokens])
- # Calculate score for each token, use as weight
- weights.append(self.score(freq[token], idf, length))
+ # Calculate score for each token, use as weight
+ weights = self.score(freq, idf, length).tolist()
# Boost weights of tag tokens to match the largest weight in the list
if self.tags:
@@ -190,7 +199,7 @@ class Scoring:
def search(self, query, limit=3):
"""
- Search index for documents matching query. Request terms config parameter to be enabled.
+ Search index for documents matching query.
Args:
query: input query
@@ -200,75 +209,44 @@ class Scoring:
list of (id, score) or (data, score) if content is enabled
"""
- # Check if document terms available
- if self.docterms:
- query = Tokenizer.tokenize(query) if isinstance(query, str) else query
+ # Check if term index available
+ if self.terms:
+ # Parse query into terms
+ query = self.tokenize(query) if isinstance(query, str) else query
- scores = {}
- for token in query:
- if token in self.docterms:
- for x in self.docterms[token]:
- if x not in scores:
- scores[x] = 0.0
+ # Get topn term query matches
+ scores = self.terms.search(query, limit)
- scores[x] += self.docterms[token][x]
+ # Normalize scores, if enabled
+ if self.normalize:
+ # Calculate max score = 4 * average score
+ maxscore = 4 * self.score(self.avgfreq, self.avgidf, self.avgdl)
- # Get topn matching results
- topn = self.topn(scores, limit)
+ # Normalize scores between 0 - 1 using maxscore
+ scores = [(x, min(score / maxscore, 1.0)) for x, score in scores]
- # Format results and add content if available
- return self.results(topn)
+ # Add content, if available
+ return self.results(scores)
return None
- def topn(self, scores, limit):
- """
- Extracts topn search results.
-
- Args:
- scores: all scores
- limit: maximum results
-
- Returns:
- topn results
+ def batchsearch(self, queries, limit=3, threads=True):
"""
-
- # Sort and get topn results
- scores = sorted(scores.items(), key=lambda x: x[1], reverse=True)[:limit]
-
- # Normalize scores, if enabled
- if self.normalize:
- # Calculate max score = 4 * average score
- maxscore = 4 * self.score(self.avgfreq, self.avgidf, self.avgdl)
-
- # Normalize scores between 0 - 1 using maxscore
- scores = [(x, min(score / maxscore, 1.0)) for x, score in scores]
-
- return scores
-
- def results(self, topn):
+ Search index for documents matching queries. This method is able to run as multiple threads due to
+ a number of regex and numpy method calls that drop the GIL.
"""
- Resolves a list of (id, score) with document content, if available. Otherwise, the original input is returned.
-
- Args:
- topn: list of (id, score)
- Returns:
- resolved results
- """
-
- if self.documents:
- results = []
- for x, score in topn:
- 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})
+ # Calculate number of threads using a thread per 25k records in index
+ threads = math.ceil(self.count() / 25000) if isinstance(threads, bool) and threads else int(threads)
+ threads = min(max(threads, 1), os.cpu_count())
- return results
+ # Run threaded queries
+ results = []
+ with ThreadPool(threads) as pool:
+ for result in pool.starmap(self.search, [(x, limit) for x in queries]):
+ results.append(result)
- return topn
+ return results
def count(self):
"""
@@ -278,7 +256,7 @@ class Scoring:
total number of documents indexed
"""
- return self.total
+ return self.terms.count() if self.terms else self.total
def load(self, path):
"""
@@ -289,8 +267,14 @@ class Scoring:
"""
with open(path, "rb") as handle:
+ # Load scoring
self.__dict__.update(pickle.load(handle))
+ # Load terms
+ if self.config.get("terms"):
+ self.terms = Terms(self.config["terms"], self.score, self.idf)
+ self.terms.load(path + ".terms")
+
def save(self, path):
"""
Saves a Scoring object to path.
@@ -300,11 +284,20 @@ class Scoring:
"""
with open(path, "wb") as handle:
- pickle.dump(self.__dict__, handle, protocol=__pickle__)
+ # Don't serialize following fields
+ skipfields = ("config", "terms", "tokenizer")
+
+ # Save scoring
+ state = {key: value for key, value in self.__dict__.items() if key not in skipfields}
+ pickle.dump(state, handle, protocol=__pickle__)
+
+ # Save terms
+ if self.terms:
+ self.terms.save(path + ".terms")
def computefreq(self, tokens):
"""
- Computes token frequency.
+ Computes token frequency. Used for token weighting.
Args:
tokens: input tokens
@@ -326,7 +319,7 @@ class Scoring:
idf score
"""
- return math.log((self.total + 1) / (freq + 1)) + 1
+ return np.log((self.total + 1) / (freq + 1)) + 1
# pylint: disable=W0613
def score(self, freq, idf, length):
@@ -342,4 +335,86 @@ class Scoring:
token score
"""
- return idf * math.sqrt(freq) * (1 / math.sqrt(length))
+ return idf * np.sqrt(freq) * (1 / np.sqrt(length))
+
+ def addstats(self, tokens, tags):
+ """
+ Add tokens and tags to stats.
+
+ Args:
+ tokens: list of tokens
+ tags: list of tags
+ """
+
+ # Total number of times token appears, count all tokens
+ self.wordfreq.update(tokens)
+
+ # Total number of documents a token is in, count unique tokens
+ self.docfreq.update(set(tokens))
+
+ # Get list of unique tags
+ if tags:
+ self.tags.update(tags.split())
+
+ # Total document count
+ self.total += 1
+
+ def tokenize(self, text):
+ """
+ Tokenizes text using default tokenizer.
+
+ Args:
+ text: input text
+
+ Returns:
+ tokens
+ """
+
+ # Load tokenizer
+ if not self.tokenizer:
+ self.tokenizer = self.loadtokenizer()
+
+ return self.tokenizer(text)
+
+ def loadtokenizer(self):
+ """
+ Load default tokenizer.
+
+ Returns:
+ tokenize method
+ """
+
+ # Custom tokenizer settings
+ if self.config.get("tokenizer"):
+ return Tokenizer(**self.config.get("tokenizer"))
+
+ # Terms index use a standard tokenizer
+ if self.config.get("terms"):
+ return Tokenizer()
+
+ # Standard scoring index without a terms index uses backwards compatible static tokenize method
+ return Tokenizer.tokenize
+
+ def results(self, scores):
+ """
+ Resolves a list of (id, score) with document content, if available. Otherwise, the original input is returned.
+
+ Args:
+ scores: list of (id, score)
+
+ Returns:
+ resolved results
+ """
+
+ 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 scores
diff --git a/src/python/txtai/scoring/bm25.py b/src/python/txtai/scoring/bm25.py
index 980908c6..3d743542 100644
--- a/src/python/txtai/scoring/bm25.py
+++ b/src/python/txtai/scoring/bm25.py
@@ -2,7 +2,7 @@
BM25 module
"""
-import math
+import numpy as np
from .base import Scoring
@@ -21,7 +21,7 @@ class BM25(Scoring):
def computeidf(self, freq):
# Calculate BM25 IDF score
- return math.log(1 + (self.total - freq + 0.5) / (freq + 0.5))
+ return np.log(1 + (self.total - freq + 0.5) / (freq + 0.5))
def score(self, freq, idf, length):
# Calculate BM25 score
diff --git a/src/python/txtai/scoring/sif.py b/src/python/txtai/scoring/sif.py
index e4bee2f6..533d16da 100644
--- a/src/python/txtai/scoring/sif.py
+++ b/src/python/txtai/scoring/sif.py
@@ -2,6 +2,8 @@
SIF module
"""
+import numpy as np
+
from .base import Scoring
@@ -18,9 +20,13 @@ class SIF(Scoring):
def computefreq(self, tokens):
# Default method computes frequency for a single entry
- # SIF uses word probabilities across entire index
- return self.wordfreq
+ # SIF uses word frequencies across entire index
+ return {token: self.wordfreq[token] for token in tokens}
def score(self, freq, idf, length):
+ # Set freq to word frequencies across entire index when freq and idf shape don't match
+ if isinstance(freq, np.ndarray) and freq.shape != idf.shape:
+ freq.fill(freq.sum())
+
# Calculate SIF score
return self.a / (self.a + freq / self.tokens)
diff --git a/src/python/txtai/scoring/terms.py b/src/python/txtai/scoring/terms.py
new file mode 100644
index 00000000..8b8a87d0
--- /dev/null
+++ b/src/python/txtai/scoring/terms.py
@@ -0,0 +1,490 @@
+"""
+Terms module
+"""
+
+import functools
+import os
+import sqlite3
+import sys
+
+from array import array
+from collections import Counter
+from threading import RLock
+
+import numpy as np
+
+
+class Terms:
+ """
+ Builds, searches and stores memory efficient term frequency sparse arrays for a scoring instance.
+ """
+
+ # Term frequency sparse arrays
+ CREATE_TERMS = """
+ CREATE TABLE IF NOT EXISTS terms (
+ term TEXT PRIMARY KEY,
+ ids BLOB,
+ freqs BLOB
+ )
+ """
+
+ INSERT_TERM = "INSERT OR REPLACE INTO terms VALUES (?, ?, ?)"
+ SELECT_TERMS = "SELECT ids, freqs FROM terms WHERE term = ?"
+
+ # Documents table
+ CREATE_DOCUMENTS = """
+ CREATE TABLE IF NOT EXISTS documents (
+ indexid INTEGER PRIMARY KEY,
+ id TEXT,
+ deleted INTEGER,
+ length INTEGER
+ )
+ """
+
+ DELETE_DOCUMENTS = "DELETE FROM documents"
+ INSERT_DOCUMENT = "INSERT OR REPLACE INTO documents VALUES (?, ?, ?, ?)"
+ SELECT_DOCUMENTS = "SELECT indexid, id, deleted, length FROM documents ORDER BY indexid"
+
+ def __init__(self, config, score, idf):
+ """
+ Creates a new terms index.
+
+ Args:
+ config: configuration
+ score: score function
+ idf: idf weights
+ """
+
+ # Terms index configuration
+ self.config = config if isinstance(config, dict) else {}
+ self.cachelimit = self.config.get("cachelimit", 250000000)
+ self.cutoff = self.config.get("cutoff", 0.1)
+
+ # Scoring function
+ self.score, self.idf = score, idf
+
+ # Document attributes
+ self.ids, self.deletes, self.lengths = [], [], array("q")
+
+ # Terms cache
+ self.terms, self.cachesize = {}, 0
+
+ # Terms database
+ self.connection, self.cursor, self.path = None, None, None
+
+ # Database thread lock
+ self.lock = RLock()
+
+ def insert(self, uid, terms):
+ """
+ Insert term into index.
+
+ Args:
+ uid: document id
+ terms: document terms
+ """
+
+ # Initialize database, if necessary
+ self.initialize()
+
+ # Get next internal index id
+ indexid = len(self.ids)
+
+ # Calculate term frequency and document length
+ freqs, length = Counter(terms), len(terms)
+
+ # Add document terms
+ for term, count in freqs.items():
+ # Add term entry
+ self.add(indexid, term, count)
+
+ # Each term and freq is a 8-bit signed long long
+ self.cachesize += 16
+
+ # Flush cached terms to the database
+ if self.cachesize >= self.cachelimit:
+ self.index()
+
+ # Save id and length
+ self.ids.append(uid)
+ self.lengths.append(length)
+
+ def delete(self, ids):
+ """
+ Mark ids as deleted. This prevents deleted results from showing up in search results.
+ The data is not removed from the underlying term frequency sparse arrays.
+
+ Args:
+ ids: ids to delete
+ """
+
+ # Set index ids as deleted
+ self.deletes.extend([self.ids.index(i) for i in ids])
+
+ def index(self):
+ """
+ Saves any remaining cached terms to the database.
+ """
+
+ for term, (nuids, nfreqs) in self.terms.items():
+ # Retrieve existing uids/freqs
+ uids, freqs = self.lookup(term)
+
+ if uids:
+ uids.extend(nuids)
+ freqs.extend(nfreqs)
+ else:
+ uids, freqs = nuids, nfreqs
+
+ # Always save as little endian
+ if sys.byteorder == "big":
+ uids.byteswap()
+ freqs.byteswap()
+
+ # Insert or replace term
+ self.cursor.execute(Terms.INSERT_TERM, [term, uids.tobytes(), freqs.tobytes()])
+
+ # Clear cached weights
+ self.weights.cache_clear()
+
+ # Reset term cache size
+ self.terms, self.cachesize = {}, 0
+
+ def search(self, terms, limit):
+ """
+ Searches term index a term-at-a-time. Each term frequency sparse array is retrieved
+ and used to calculate term match scores.
+
+ This method calculates term scores in two steps as shown below.
+
+ 1. Query and score less common term scores first
+ 2. Merge in common term scores for all documents matching the first query
+
+ This is similar to the common terms query in Apache Lucene.
+
+ Args:
+ terms: query terms
+ limit: maximum results
+
+ Returns:
+ list of (id, score)
+ """
+
+ # Initialize scores array
+ scores = np.zeros(len(self.ids), dtype=np.float32)
+
+ # Score less common terms
+ terms, skipped, hasscores = Counter(terms), {}, False
+ for term, freq in terms.items():
+ # Compute or lookup term weights
+ uids, weights = self.weights(term)
+ if uids is not None:
+ # Term considered common if it appears in more than 10% of index
+ if len(uids) <= self.cutoff * len(self.ids):
+ # Add scores
+ scores[uids] += freq * weights
+
+ # Set flag that scores have been calculated for at least one term
+ hasscores = True
+ else:
+ skipped[term] = freq
+
+ # Merge in common term scores and return top n matches
+ return self.topn(scores, limit, hasscores, skipped)
+
+ def count(self):
+ """
+ Number of elements in the scoring index.
+
+ Returns:
+ count
+ """
+
+ return len(self.ids) - len(self.deletes)
+
+ def load(self, path):
+ """
+ Loads terms database from path. This method loads document attributes into memory.
+
+ Args:
+ path: path to read terms database
+ """
+
+ # Load an existing terms database
+ self.connection = self.connect(path)
+ self.cursor = self.connection.cursor()
+ self.path = path
+
+ # Load document attributes
+ self.ids, self.deletes, self.lengths = [], [], array("q")
+
+ self.cursor.execute(Terms.SELECT_DOCUMENTS)
+ for indexid, uid, deleted, length in self.cursor:
+ # Index id - id
+ self.ids.append(uid)
+
+ # Deleted flag
+ if deleted:
+ self.deletes.append(indexid)
+
+ # Index id - length
+ self.lengths.append(length)
+
+ # Cast ids to int if every id is an integer
+ if all(uid.isdigit() for uid in self.ids):
+ self.ids = [int(uid) for uid in self.ids]
+
+ # Clear cache
+ self.weights.cache_clear()
+
+ def save(self, path):
+ """
+ Saves terms database to path. This method creates or replaces document attributes into the database.
+
+ Args:
+ path: path to write terms database
+ """
+
+ # Clear documents table
+ self.cursor.execute(Terms.DELETE_DOCUMENTS)
+
+ # Save document attributes
+ for i, uid in enumerate(self.ids):
+ self.cursor.execute(Terms.INSERT_DOCUMENT, [i, uid, 1 if i in self.deletes else 0, self.lengths[i]])
+
+ # Temporary database
+ if not self.path:
+ # Save temporary database
+ self.connection.commit()
+
+ # Copy data from current to new
+ connection = self.copy(path)
+
+ # Close temporary database
+ self.connection.close()
+
+ # Point connection to new connection
+ self.connection = connection
+ self.cursor = self.connection.cursor()
+ self.path = path
+
+ # Paths are equal, commit changes
+ elif self.path == path:
+ self.connection.commit()
+
+ # New path is different from current path, copy data and continue using current connection
+ else:
+ self.copy(path).close()
+
+ def initialize(self):
+ """
+ Creates connection and initial database schema if no connection exists.
+ """
+
+ if not self.connection:
+ # Create term database
+ self.connection = self.connect()
+ self.cursor = self.connection.cursor()
+
+ # Create initial schema
+ self.cursor.execute(Terms.CREATE_TERMS)
+ self.cursor.execute(Terms.CREATE_DOCUMENTS)
+
+ def connect(self, path=""):
+ """
+ Creates a new term database connection.
+
+ Args:
+ path: path to term database file
+
+ Returns:
+ connection
+ """
+
+ connection = sqlite3.connect(path, check_same_thread=False)
+
+ # Enable WAL mode, if necessary
+ if self.config.get("wal"):
+ connection.execute("PRAGMA journal_mode=WAL")
+
+ return connection
+
+ def copy(self, path):
+ """
+ Copies content from current terms database into target.
+
+ Args:
+ path: target database path
+
+ Returns:
+ new database connection
+ """
+
+ # Delete existing file, if necessary
+ if os.path.exists(path):
+ os.remove(path)
+
+ # Create new connection
+ connection = self.connect(path)
+
+ if self.connection.in_transaction:
+ # The backup call will hang if there are uncommitted changes, need to copy over
+ # with iterdump (which is much slower)
+ for sql in self.connection.iterdump():
+ connection.execute(sql)
+ else:
+ # Database is up to date, can do a more efficient copy with SQLite C API
+ self.connection.backup(connection)
+
+ return connection
+
+ def add(self, indexid, term, freq):
+ """
+ Adds a term frequency entry.
+
+ Args:
+ indexid: internal index id
+ term: term
+ freq: term frequency
+ """
+
+ # Get or create uids and freqs arrays
+ if term not in self.terms:
+ self.terms[term] = (array("q"), array("q"))
+
+ # Append uids and freqs
+ ids, freqs = self.terms[term]
+ ids.append(indexid)
+ freqs.append(freq)
+
+ def lookup(self, term):
+ """
+ Retrieves a term frequency sparse array.
+
+ Args:
+ term: term to lookup
+
+ Returns:
+ term frequency sparse array
+ """
+
+ uids, freqs = None, None
+
+ result = self.cursor.execute(Terms.SELECT_TERMS, [term]).fetchone()
+ if result:
+ uids, freqs = (array("q"), array("q"))
+ uids.frombytes(result[0])
+ freqs.frombytes(result[1])
+
+ # Storage format is always little endian
+ if sys.byteorder == "big":
+ uids.byteswap()
+ freqs.byteswap()
+
+ return uids, freqs
+
+ @functools.lru_cache(maxsize=500)
+ def weights(self, term):
+ """
+ Computes a term weights sparse array for term. This method is wrapped with a least recently used cache,
+ which will return common term weights from the cache.
+
+ Args:
+ term: term
+
+ Returns:
+ term weights sparse array
+ """
+
+ lengths = np.frombuffer(self.lengths, dtype=np.int64)
+
+ with self.lock:
+ uids, freqs = self.lookup(term)
+ weights = None
+
+ if uids:
+ uids = np.frombuffer(uids, dtype=np.int64)
+ weights = self.score(np.frombuffer(freqs, dtype=np.int64), self.idf[term], lengths[uids]).astype(np.float32)
+
+ return uids, weights
+
+ def topn(self, scores, limit, hasscores, skipped):
+ """
+ Get topn scores from an partial scores array.
+
+ Args:
+ scores: partial scores array with scores for less common terms
+ limit: maximum results
+ hasscores: True if partial scores array has any nonzero scores, False otherwise
+ skipped: terms skipped in initial query
+
+ Returns:
+ topn scores
+ """
+
+ # Calculate topn candidates to consider
+ # Require at least one positive score, set topn to smaller of limit * 5 or number of scores
+ topn = min(len(scores), limit * 5)
+
+ # Get topn candidates, allows for score shifting when adding in common term scores
+ matches = self.candidates(scores, topn)
+
+ # Merge in scores for more common terms
+ self.merge(scores, matches, hasscores, skipped)
+
+ # Get topn candidates since it was initially skipped above
+ if not hasscores:
+ matches = self.candidates(scores, topn)
+
+ # Reorder matches using updated scores
+ 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]
+
+ def merge(self, scores, matches, hasscores, terms):
+ """
+ Merges common term scores into scores array.
+
+ Args:
+ scores: partial scores array
+ matches: current matches, if any
+ hasscores: True if scores has current matches, False otherwise
+ terms: common terms
+ """
+
+ for term, freq in terms.items():
+ # Compute or lookup term weights
+ uids, weights = self.weights(term)
+
+ # Filter to topn matches when partial scores array has nonzero scores
+ if hasscores:
+ # Find indices in match ids for uids
+ indices = np.searchsorted(uids, matches)
+
+ # Filter matches that don't exist in uids
+ indices = [x for i, x in enumerate(indices) if x < len(uids) and uids[x] == matches[i]]
+
+ # Filter to matching uids and weights
+ uids, weights = uids[indices], weights[indices]
+
+ # Update scores
+ scores[uids] += freq * weights
+
+ def candidates(self, scores, topn):
+ """
+ Gets the topn scored candidates. This method ignores deleted documents.
+
+ Args:
+ scores: scores array
+ topn: topn elements
+
+ Returns:
+ topn scored candidates
+ """
+
+ # Clear deletes
+ scores[self.deletes] = 0
+
+ # Get topn candidates
+ return np.argpartition(scores, -topn)[-topn:]
diff --git a/test/python/testscoring.py b/test/python/testscoring.py
index 9f4fd73e..a46570f1 100644
--- a/test/python/testscoring.py
+++ b/test/python/testscoring.py
@@ -6,6 +6,8 @@ import os
import tempfile
import unittest
+from unittest.mock import patch
+
from txtai.scoring import ScoringFactory
@@ -71,11 +73,14 @@ class TestScoring(unittest.TestCase):
config = {"method": method}
self.index(config)
+ self.upsert(config)
self.weights(config)
self.search(config)
+ self.delete(config)
self.normalize(config)
self.content(config)
self.empty(config)
+ self.settings(config)
def index(self, config, data=None):
"""
@@ -86,50 +91,70 @@ class TestScoring(unittest.TestCase):
data: data to index with scoring method
Returns:
- Scoring model
+ scoring
"""
# Derive input data
data = data if data else self.data
- model = ScoringFactory.create(config)
- model.index(data)
+ scoring = ScoringFactory.create(config)
+ scoring.index(data)
- keys = [k for k, v in sorted(model.idf.items(), key=lambda x: x[1])]
+ keys = [k for k, v in sorted(scoring.idf.items(), key=lambda x: x[1])]
# Test count
- self.assertEqual(model.count(), len(data))
+ self.assertEqual(scoring.count(), len(data))
- # Win should be lowest score for all models
+ # Win should be lowest score
self.assertEqual(keys[0], "wins")
# Test save/load
- self.assertIsNotNone(self.save(model))
+ self.assertIsNotNone(self.save(scoring, config))
# Test search returns none when terms disabled (default)
- self.assertIsNone(model.search("query"))
+ self.assertIsNone(scoring.search("query"))
- return model
+ return scoring
- def save(self, model):
+ def upsert(self, config):
+ """
+ Test scoring upsert method
+ """
+
+ scoring = ScoringFactory.create({**config, **{"tokenizer": {"alphanum": True, "stopwords": True}}})
+ scoring.upsert(self.data)
+
+ # Test count
+ self.assertEqual(scoring.count(), len(self.data))
+
+ # Test stop word is removed
+ self.assertFalse("and" in scoring.idf)
+
+ def save(self, scoring, config, name="scoring"):
"""
Test scoring index save/load.
Args:
- model: Scoring model
+ scoring: scoring index
+ config: scoring config
+ name: output file name
Returns:
- Scoring model
+ scoring
"""
# Generate temp file path
index = os.path.join(tempfile.gettempdir(), "scoring")
os.makedirs(index, exist_ok=True)
- model.save(f"{index}/scoring")
- model.load(f"{index}/scoring")
+ # Save scoring instance
+ scoring.save(f"{index}/{name}")
- return model
+ # Reload scoring instance
+ scoring = ScoringFactory.create(config)
+ scoring.load(f"{index}/{name}")
+
+ return scoring
def weights(self, config):
"""
@@ -173,6 +198,36 @@ class TestScoring(unittest.TestCase):
index, _ = scoring.search("bear", 1)[0]
self.assertEqual(index, 3)
+ # Run batch search
+ index, _ = scoring.batchsearch(["bear"], 1)[0][0]
+ self.assertEqual(index, 3)
+
+ # Test save/reload
+ self.save(scoring, config)
+
+ # Re-run search and validate correct result returned
+ index, _ = scoring.search("bear", 1)[0]
+ self.assertEqual(index, 3)
+
+ def delete(self, config):
+ """
+ Test delete.
+ """
+
+ scoring = ScoringFactory.create({**config, **{"terms": True, "content": True}})
+ scoring.index(self.data)
+
+ # Run search and validate correct result returned
+ index = scoring.search("bear", 1)[0]["id"]
+
+ # Delete result and validate the query no longer returns results
+ scoring.delete([index])
+ self.assertFalse(scoring.search("bear", 1))
+
+ # Save and validate count
+ self.save(scoring, config)
+ self.assertEqual(scoring.count(), len(self.data) - 1)
+
def normalize(self, config):
"""
Test scoring search with normalized scores.
@@ -230,3 +285,30 @@ class TestScoring(unittest.TestCase):
# Assert index call returns and index has a count of 0
self.assertEqual(scoring.total, 0)
+
+ @patch("sys.byteorder", "big")
+ def settings(self, config):
+ """
+ Tests various settings.
+
+ Args:
+ config: scoring config
+ """
+
+ scoring = ScoringFactory.create({**config, **{"terms": {"cachelimit": 0, "cutoff": 0.25, "wal": True}}})
+ scoring.index(self.data)
+
+ # Save/load index
+ self.save(scoring, config)
+
+ index, _ = scoring.search("bear bear bear wins", 1)[0]
+ self.assertEqual(index, 3)
+
+ # Save to same path
+ self.save(scoring, config)
+
+ # Save to different path
+ self.save(scoring, config, "scoring.move")
+
+ # Validate counts
+ self.assertEqual(scoring.count(), len(self.data))