Skip to content

armgit / txtai

Public Imported from GitHub
0

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

Consistently name embeddings id fields, closes #178

davidmezzettif84ed38c1b8f
diff --git a/src/python/txtai/database/base.py b/src/python/txtai/database/base.py
index 4d69c2d6..e0338c3d 100644
--- a/src/python/txtai/database/base.py
+++ b/src/python/txtai/database/base.py
@@ -47,17 +47,17 @@ class Database:
Args:
documents: list of documents to save
- index: index id offset, used for internal ids
+ index: indexid offset, used for internal ids
"""
raise NotImplementedError
- def delete(self, uids):
+ def delete(self, ids):
"""
Deletes documents from database.
Args:
- uids: uids to delete
+ ids: ids to delete
"""
raise NotImplementedError
@@ -69,16 +69,16 @@ class Database:
raise NotImplementedError
- def ids(self, uids):
+ def ids(self, ids):
"""
- Retrieves the internal ids for a list of uids. Multiple ids may be present for a uid in cases
+ Retrieves the internal indexids for a list of ids. Multiple indexids may be present for an id in cases
where text is segmented.
Args:
- uids: list of document uids
+ ids: list of document ids
Returns:
- list of (id, uid)
+ list of (indexid, id)
"""
raise NotImplementedError
@@ -101,7 +101,7 @@ class Database:
Args:
query: input query
- similarity: similarity results as [(id, score)]
+ similarity: similarity results as [(indexid, score)]
limit: maximum number of results to return
Returns:
@@ -163,7 +163,7 @@ class Database:
Embeds similarity query results into a database query.
Args:
- similarity: similarity results as [(id, score)]
+ similarity: similarity results as [(indexid, score)]
batch: batch id
"""
diff --git a/src/python/txtai/database/sql/base.py b/src/python/txtai/database/sql/base.py
index b3df51c1..5a03cf1e 100644
--- a/src/python/txtai/database/sql/base.py
+++ b/src/python/txtai/database/sql/base.py
@@ -78,7 +78,7 @@ class SQL:
True if this is a valid SQL query, False otherwise
"""
- query = query.lower()
+ query = query.lower().strip(";")
return query.startswith("select ") and (" from txtai " in query or query.endswith(" from txtai"))
def tokenize(self, query):
@@ -92,8 +92,14 @@ class SQL:
(tokenized query, token positions)
"""
- # Build a simple SQL lexer - punctuation chars are parsed as standalone tokens which helps identify operators
- tokens = list(shlex(StringIO(query), punctuation_chars="=!<>+-*/%"))
+ # Build a simple SQL lexer
+ # - Punctuation chars are parsed as standalone tokens which helps identify operators
+ # - Add additional wordchars to prevent splitting on those values
+ # - Disable comments
+ tokens = shlex(StringIO(query), punctuation_chars="=!<>+-*/%")
+ tokens.wordchars += ":@#"
+ tokens.commenters = ""
+ tokens = list(tokens)
# Identify sql clause token positions
positions = {}
diff --git a/src/python/txtai/database/sql/expression.py b/src/python/txtai/database/sql/expression.py
index db6d8977..ed43e448 100644
--- a/src/python/txtai/database/sql/expression.py
+++ b/src/python/txtai/database/sql/expression.py
@@ -37,7 +37,7 @@ class Expression:
Args:
tokens: input expression
- alias: If True, column aliases should be generated
+ alias: if True, column aliases should be generated
similar: list of similar queries, if present new similar queries are appended to this list
Returns:
@@ -56,7 +56,7 @@ class Expression:
Args:
tokens: input expression
- alias: If True, column aliases should be generated
+ alias: if True, column aliases should be generated
similar: list of similar queries, if present new similar queries are appended to this list
Returns:
@@ -199,7 +199,7 @@ class Expression:
Args:
tokens: input tokens
x: current token position
- alias: If True, column aliases should be generated
+ alias: if True, column aliases should be generated
"""
# Alias name
@@ -221,7 +221,7 @@ class Expression:
iterator: tokens iterator
tokens: input tokens
x: current token position
- alias: If True, column aliases should be generated
+ alias: if True, column aliases should be generated
"""
# Alias name
@@ -314,7 +314,7 @@ class Expression:
True if this token is a literal, False otherwise
"""
- return token and (token.startswith(("'", '"', ",", "(", ")", "[", "]", "*")) or token.isnumeric())
+ return token and (token.startswith(("'", '"', ",", "(", ")", "[", "]", "*")) or token.replace(".", "", 1).isdigit())
def wrapspace(self, text, token):
"""
@@ -340,7 +340,7 @@ class Expression:
if token in [","]:
return f"{token} "
- # No whitespace if any of the following is true
+ # No whitespace if any of the following is True
if not text or text.endswith((" ", "(", "[")) or token in ["(", "[", ")", "]"]:
return token
diff --git a/src/python/txtai/database/sqlite.py b/src/python/txtai/database/sqlite.py
index 7d77b366..0e665602 100644
--- a/src/python/txtai/database/sqlite.py
+++ b/src/python/txtai/database/sqlite.py
@@ -18,8 +18,8 @@ class SQLite(Database):
# Temporary table for working with id batches
CREATE_BATCH = """
CREATE TEMP TABLE IF NOT EXISTS batch (
- id INTEGER,
- uid TEXT,
+ indexid INTEGER,
+ id TEXT,
batch INTEGER
)
"""
@@ -30,7 +30,7 @@ class SQLite(Database):
# Temporary table for joining similarity scores
CREATE_SCORES = """
CREATE TEMP TABLE IF NOT EXISTS scores (
- id INTEGER,
+ indexid INTEGER,
score REAL
)
"""
@@ -41,7 +41,7 @@ class SQLite(Database):
# Documents - stores full content
CREATE_DOCUMENTS = """
CREATE TABLE IF NOT EXISTS documents (
- uid TEXT PRIMARY KEY,
+ id TEXT PRIMARY KEY,
data JSON,
tags TEXT,
entry DATETIME
@@ -49,29 +49,29 @@ class SQLite(Database):
"""
INSERT_DOCUMENT = "INSERT INTO documents VALUES (?, ?, ?, ?)"
- DELETE_DOCUMENTS = "DELETE FROM documents WHERE uid IN (SELECT uid FROM batch)"
+ DELETE_DOCUMENTS = "DELETE FROM documents WHERE id IN (SELECT id FROM batch)"
# Sections - stores section text
CREATE_SECTIONS = """
CREATE TABLE IF NOT EXISTS sections (
- id INTEGER PRIMARY KEY,
- uid TEXT,
+ indexid INTEGER PRIMARY KEY,
+ id TEXT,
text TEXT,
tags TEXT,
entry DATETIME
)
"""
- CREATE_SECTIONS_INDEX = "CREATE INDEX section_uid ON sections(uid)"
+ CREATE_SECTIONS_INDEX = "CREATE INDEX section_id ON sections(id)"
INSERT_SECTION = "INSERT INTO sections VALUES (?, ?, ?, ?, ?)"
- DELETE_SECTIONS = "DELETE FROM sections WHERE uid IN (SELECT uid FROM batch)"
+ DELETE_SECTIONS = "DELETE FROM sections WHERE id IN (SELECT id FROM batch)"
# Queries
- SELECT_IDS = "SELECT id, uid FROM sections WHERE uid in (SELECT uid FROM batch)"
+ SELECT_IDS = "SELECT indexid, id FROM sections WHERE id in (SELECT id FROM batch)"
# Partial sql clauses
- TABLE_CLAUSE = "SELECT %s FROM sections s LEFT JOIN documents d ON s.uid = d.uid LEFT JOIN scores sc on s.id=sc.id"
- IDS_CLAUSE = "s.id in (SELECT id from batch WHERE batch=%s)"
+ TABLE_CLAUSE = "SELECT %s FROM sections s LEFT JOIN documents d ON s.id = d.id LEFT JOIN scores sc on s.indexid=sc.indexid"
+ IDS_CLAUSE = "s.indexid in (SELECT indexid from batch WHERE batch=%s)"
def __init__(self, config):
"""
@@ -89,8 +89,8 @@ class SQLite(Database):
self.path = None
def load(self, path):
- # Load an existing database
- self.connection = sqlite3.connect(path)
+ # Load an existing database. Thread locking must be handled externally.
+ self.connection = sqlite3.connect(path, check_same_thread=False)
self.cursor = self.connection.cursor()
self.path = path
@@ -119,10 +119,10 @@ class SQLite(Database):
self.cursor.execute(SQLite.INSERT_SECTION, [index, uid, document, tags, entry])
index += 1
- def delete(self, uids):
+ def delete(self, ids):
if self.connection:
# Batch ids
- self.batch(uids=uids)
+ self.batch(ids=ids)
# Delete all documents and sections by id
self.cursor.execute(SQLite.DELETE_DOCUMENTS)
@@ -138,8 +138,8 @@ class SQLite(Database):
if os.path.exists(path):
os.remove(path)
- # Create database
- connection = sqlite3.connect(path)
+ # Create database. Thread locking must be handled externally.
+ connection = sqlite3.connect(path, check_same_thread=False)
# Copy from existing database to new database
self.connection.backup(connection)
@@ -150,9 +150,9 @@ class SQLite(Database):
self.cursor = self.connection.cursor()
self.path = path
- def ids(self, uids):
- # Batch uids and run query
- self.batch(uids=uids)
+ def ids(self, ids):
+ # Batch ids and run query
+ self.batch(ids=ids)
self.cursor.execute(SQLite.SELECT_IDS)
# Format and return results
@@ -201,7 +201,7 @@ class SQLite(Database):
def resolve(self, name, alias=False, compound=False):
# Standard column names
- sections = ["id", "uid", "tags", "entry"]
+ sections = ["indexid", "id", "tags", "entry"]
noprefix = ["data", "score", "text"]
# Alias JSON column expressions
@@ -226,7 +226,7 @@ class SQLite(Database):
def embed(self, similarity, batch):
# Load similarity results id batch
- self.batch(ids=[i for i, _ in similarity[batch]], batch=batch)
+ self.batch(indexids=[i for i, _ in similarity[batch]], batch=batch)
# Average and load all similarity scores with first batch
if not batch:
@@ -241,8 +241,8 @@ class SQLite(Database):
"""
if not self.connection:
- # Create temporary database
- self.connection = sqlite3.connect("")
+ # Create temporary database. Thread locking must be handled externally.
+ self.connection = sqlite3.connect("", check_same_thread=False)
self.cursor = self.connection.cursor()
# Create initial schema and indices
@@ -250,13 +250,13 @@ class SQLite(Database):
self.cursor.execute(SQLite.CREATE_SECTIONS)
self.cursor.execute(SQLite.CREATE_SECTIONS_INDEX)
- def batch(self, ids=None, uids=None, batch=None):
+ def batch(self, indexids=None, ids=None, batch=None):
"""
Loads ids to a temporary batch table for efficient query processing.
Args:
+ indexids: list of indexids
ids: list of ids
- uids: list of uids
batch: batch index, used when statement has multiple subselects
"""
@@ -267,17 +267,17 @@ class SQLite(Database):
if not batch:
self.cursor.execute(SQLite.DELETE_BATCH)
+ if indexids:
+ self.cursor.executemany(SQLite.INSERT_BATCH, [(i, None, batch) for i in indexids])
if ids:
- self.cursor.executemany(SQLite.INSERT_BATCH, [(i, None, batch) for i in ids])
- else:
- self.cursor.executemany(SQLite.INSERT_BATCH, [(None, str(uid), batch) for uid in uids])
+ self.cursor.executemany(SQLite.INSERT_BATCH, [(None, str(uid), batch) for uid in ids])
def scores(self, similarity):
"""
Loads a batch of similarity scores to a temporary table for efficient query processing.
Args:
- similarity: similarity results as [(id, score)]
+ similarity: similarity results as [(indexid, score)]
"""
# Create or Replace temporary scores table
diff --git a/src/python/txtai/embeddings/base.py b/src/python/txtai/embeddings/base.py
index 23c602ea..5950f494 100644
--- a/src/python/txtai/embeddings/base.py
+++ b/src/python/txtai/embeddings/base.py
@@ -20,14 +20,15 @@ from .search import Search
class Embeddings:
"""
Embeddings is the engine that delivers semantic search. Text is transformed into embeddings vectors where similar concepts
- will produce similar vectors. Indices both large and small are built with these vectors. The indices are used find results
+ will produce similar vectors. Indexes both large and small are built with these vectors. The indexes are used find results
that have the same meaning, not necessarily the same keywords.
"""
# pylint: disable = W0231
def __init__(self, config=None):
"""
- Creates a new Embeddings model.
+ Creates a new Embeddings model. Embeddings instances are thread-safe for read operations but writes must be
+ synchronized.
Args:
config: embeddings configuration
@@ -99,7 +100,7 @@ class Embeddings:
# Add documents to database
self.database.insert(documents)
else:
- # Save ids for indices with no database
+ # Save indexids-ids mapping for indexes with no database
self.config["ids"] = ids
def upsert(self, documents):
@@ -136,7 +137,7 @@ class Embeddings:
# Add documents to database
self.database.insert(documents, offset)
else:
- # Save ids for indices with no database
+ # Save indexids-ids mapping for indexes with no database
self.config["ids"] = self.config["ids"] + ids
def delete(self, ids):
@@ -157,7 +158,7 @@ class Embeddings:
deletes = []
if self.database:
- # Retrieve id-uid mappings from database
+ # Retrieve indexid-id mappings from database
ids = self.database.ids(ids)
# Parse out indices and ids to delete
@@ -167,17 +168,17 @@ class Embeddings:
# Delete ids from database
self.database.delete(deletes)
else:
- # Lookup ids from config for indices with no database
- cids = self.config["ids"]
+ # Lookup indexids from config for indexes with no database
+ indexids = self.config["ids"]
# Find existing ids
for uid in ids:
- indices.extend([index for index, value in enumerate(cids) if uid == value])
+ indices.extend([index for index, value in enumerate(indexids) if uid == value])
# Clear config ids
for index in indices:
- deletes.append(cids[index])
- cids[index] = None
+ deletes.append(indexids[index])
+ indexids[index] = None
# Delete indices from ann embeddings
if indices:
@@ -244,7 +245,7 @@ class Embeddings:
limit: maximum results
Returns:
- list of (id, score) for ann seach, list of dict for an ann+database search
+ list of (id, score) for ann search, list of dict for an ann+database search
"""
return self.batchsearch([query], limit)[0]
@@ -300,7 +301,7 @@ class Embeddings:
# Dot product on normalized vectors is equal to cosine similarity
scores = np.dot(queries, texts.T).tolist()
- # Add index id and sort desc based on score
+ # Add index and sort desc based on score
return [sorted(enumerate(score), key=lambda x: x[1], reverse=True) for score in scores]
def load(self, path):
@@ -349,7 +350,7 @@ class Embeddings:
path: input directory path
Returns:
- true if index exists, false otherwise
+ True if index exists, False otherwise
"""
return os.path.exists(f"{path}/config") and os.path.exists(f"{path}/embeddings")
@@ -413,7 +414,7 @@ class Embeddings:
"""
# Transform documents to embeddings vectors
- ids, dimensions, stream = self.model.index(self.hastext(documents))
+ ids, dimensions, stream = self.model.index(self.gettext(documents))
# Load streamed embeddings back to memory
embeddings = np.empty((len(ids), dimensions), dtype=np.float32)
@@ -440,7 +441,7 @@ class Embeddings:
else:
embeddings /= np.linalg.norm(embeddings)
- def hastext(self, documents):
+ def gettext(self, documents):
"""
Selects documents that have text to vectorize for similarity indexing.
diff --git a/src/python/txtai/embeddings/search.py b/src/python/txtai/embeddings/search.py
index 0a157e45..9df4233b 100644
--- a/src/python/txtai/embeddings/search.py
+++ b/src/python/txtai/embeddings/search.py
@@ -66,7 +66,7 @@ class Search:
# Require scores to be greater than 0
results = [[(i, score) for i, score in r if score > 0] for r in results]
- # Map internal ids to uids if "ids" available
+ # Map indexids to ids if "ids" available
if "ids" in self.config:
lookup = self.config["ids"]
return [[(lookup[i], score) for i, score in r] for r in results]
diff --git a/test/python/testdatabase/testsql.py b/test/python/testdatabase/testsql.py
index c2723376..19a18dc0 100644
--- a/test/python/testdatabase/testsql.py
+++ b/test/python/testdatabase/testsql.py
@@ -89,9 +89,9 @@ class TestSQL(unittest.TestCase):
Test basic select clauses
"""
- self.assertSql("select", "select id, uid, tags from txtai", "s.id, s.uid, s.tags")
- self.assertSql("select", "select id, uid, flag from txtai", 's.id, s.uid, json_extract(data, "$.flag") as "flag"')
- self.assertSql("select", "select id, uid, a.b.c from txtai", 's.id, s.uid, json_extract(data, "$.a.b.c") as "a.b.c"')
+ self.assertSql("select", "select id, indexid, tags from txtai", "s.id, s.indexid, s.tags")
+ self.assertSql("select", "select id, indexid, flag from txtai", 's.id, s.indexid, json_extract(data, "$.flag") as "flag"')
+ self.assertSql("select", "select id, indexid, a.b.c from txtai", 's.id, s.indexid, json_extract(data, "$.a.b.c") as "a.b.c"')
self.assertSql("select", "select 'id', [id], (id) from txtai", "'id', [s.id], (s.id)")
self.assertSql("select", "select * from txtai", "*")
@@ -122,6 +122,7 @@ class TestSQL(unittest.TestCase):
self.assertSql("where", prefix + "WHERE a NOT LIKE 'abc'", "json_extract(data, \"$.a\") NOT LIKE 'abc'")
self.assertSql("where", prefix + "WHERE a IN (1, 2, 3, b)", 'json_extract(data, "$.a") IN (1, 2, 3, json_extract(data, "$.b"))')
self.assertSql("where", prefix + "WHERE a is not null", 'json_extract(data, "$.a") is not null')
+ self.assertSql("where", prefix + "WHERE score >= 0.15", "score >= 0.15")
def testWhereCompound(self):
"""
@@ -140,7 +141,7 @@ class TestSQL(unittest.TestCase):
prefix + "where a > f(d(b, c, 1),1)",
'json_extract(data, "$.a") > f(d(json_extract(data, "$.b"), json_extract(data, "$.c"), 1), 1)',
)
- self.assertSql("where", prefix + "where (id = 1 AND id = 2) OR uid = 3", "(s.id = 1 AND s.id = 2) OR s.uid = 3")
+ self.assertSql("where", prefix + "where (id = 1 AND id = 2) OR indexid = 3", "(s.id = 1 AND s.id = 2) OR s.indexid = 3")
self.assertSql("where", prefix + "where f(id) = b(id)", "f(s.id) = b(s.id)")
self.assertSql("where", prefix + "WHERE f(id)", "f(s.id)")