Skip to content

armgit / txtai

Public Imported from GitHub
0

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

Initial version of storing document content (closes #168), inserting dictionaries (closes #169) and SQL query support (closes #170)

davidmezzetti345d092fab92
diff --git a/examples/console.py b/examples/console.py
new file mode 100644
index 00000000..7272e728
--- /dev/null
+++ b/examples/console.py
@@ -0,0 +1,58 @@
+"""
+txtai console module.
+
+Requires streamlit to be installed.
+ pip install streamlit
+"""
+
+import sys
+
+from cmd import Cmd
+
+from tabulate import tabulate
+from txtai.embeddings import Embeddings
+
+
+class Console(Cmd):
+ """
+ txtai console.
+ """
+
+ def __init__(self, path):
+ super().__init__()
+
+ self.intro = "txtai console"
+ self.prompt = ">>> "
+
+ self.embeddings = None
+ self.path = path
+
+ def preloop(self):
+ print(f"Loading model {self.path}")
+
+ # Load model
+ self.embeddings = Embeddings()
+ self.embeddings.load(self.path)
+
+ def default(self, line):
+ # pylint: disable=W0703
+ try:
+ results = self.embeddings.search(line)
+ print(tabulate(results, headers="keys", tablefmt="psql"))
+ except Exception as ex:
+ print(ex)
+
+
+def main(path=None):
+ """
+ Console execution loop.
+
+ Args:
+ path: model path
+ """
+
+ Console(path).cmdloop()
+
+
+if __name__ == "__main__":
+ main(sys.argv[1] if len(sys.argv) > 1 else None)
diff --git a/src/python/txtai/database/__init__.py b/src/python/txtai/database/__init__.py
new file mode 100644
index 00000000..465f6b3a
--- /dev/null
+++ b/src/python/txtai/database/__init__.py
@@ -0,0 +1,8 @@
+"""
+Database imports
+"""
+
+from .base import Database
+from .factory import DatabaseFactory
+from .sqlite import SQLite
+from .sql import *
diff --git a/src/python/txtai/database/base.py b/src/python/txtai/database/base.py
new file mode 100644
index 00000000..4d69c2d6
--- /dev/null
+++ b/src/python/txtai/database/base.py
@@ -0,0 +1,204 @@
+"""
+Database module
+"""
+
+import logging
+
+from .sql import Expression, SQL, SQLException
+
+# Logging configuration
+logger = logging.getLogger(__name__)
+logging.basicConfig(format="%(asctime)s %(levelname)s [%(name)s:%(lineno)s] %(message)s")
+
+
+class Database:
+ """
+ Base class for database instances. This class encapsulates a document-oriented database
+ used for storing key-value content stored as dicts.
+ """
+
+ def __init__(self, config):
+ """
+ Creates a new Database.
+
+ Args:
+ config: database configuration parameters
+ """
+
+ # Database configuration
+ self.config = config
+
+ # SQL parser
+ self.sql = SQL(self)
+
+ def load(self, path):
+ """
+ Loads a database path.
+
+ Args:
+ path: database url
+ """
+
+ raise NotImplementedError
+
+ def insert(self, documents, index=0):
+ """
+ Inserts documents into the database.
+
+ Args:
+ documents: list of documents to save
+ index: index id offset, used for internal ids
+ """
+
+ raise NotImplementedError
+
+ def delete(self, uids):
+ """
+ Deletes documents from database.
+
+ Args:
+ uids: uids to delete
+ """
+
+ raise NotImplementedError
+
+ def save(self, path):
+ """
+ Saves a database at path.
+ """
+
+ raise NotImplementedError
+
+ def ids(self, uids):
+ """
+ Retrieves the internal ids for a list of uids. Multiple ids may be present for a uid in cases
+ where text is segmented.
+
+ Args:
+ uids: list of document uids
+
+ Returns:
+ list of (id, uid)
+ """
+
+ raise NotImplementedError
+
+ def search(self, query, similarity=None, limit=None):
+ """
+ Runs a search against the database. Supports the following methods:
+
+ 1. Standard similarity query. This mode retrieves content for the ids in the similarity results
+ 2. Similarity query as SQL. This mode will combine similarity results and database results into
+ a single result set. Similarity queries are set via the SIMILAR() function.
+ 3. SQL with no similarity query. This mode runs a SQL query and retrieves the results without similarity queries.
+
+ Example queries:
+ "natural language processing" - standard similarity only query
+ "select * from txtai where similar('natural language processing')" - similarity query as SQL
+ "select * from txtai where similar('nlp') and entry > '2021-01-01'" - similarity query with additional SQL clauses
+ "select id, text, score from txtai where similar('nlp')" - similarity query with additional SQL column selections
+ "select * from txtai where entry > '2021-01-01' - database only query
+
+ Args:
+ query: input query
+ similarity: similarity results as [(id, score)]
+ limit: maximum number of results to return
+
+ Returns:
+ query results as a list of dicts
+ """
+
+ # Parse query if necessary
+ if isinstance(query, str):
+ query = self.parse(query)
+
+ # Add in similar results
+ where = query.get("where")
+
+ if "select" in query and similarity:
+ for x in range(len(similarity)):
+ token = f"{Expression.SIMILAR_TOKEN}{x}"
+ if where and token in where:
+ where = where.replace(token, self.embed(similarity, x))
+ elif similarity:
+ # Not a SQL query, load similarity results, if any
+ where = self.embed(similarity, 0)
+
+ # Save where
+ query["where"] = where
+
+ # Run query
+ return self.query(query, limit)
+
+ def parse(self, query):
+ """
+ Parses a query into query components.
+
+ Args:
+ query: input query
+
+ Returns:
+ dict of parsed query components
+ """
+
+ return self.sql(query)
+
+ def resolve(self, name, alias=False, compound=False):
+ """
+ Resolves a query column name with the database column name.
+
+ Args:
+ name: query column name
+ alias: True if an alias clause should be added, defaults to False
+ compound: True if this column is part of a compound expression, defaults to False
+
+ Returns:
+ database column name
+ """
+
+ raise NotImplementedError
+
+ def embed(self, similarity, batch):
+ """
+ Embeds similarity query results into a database query.
+
+ Args:
+ similarity: similarity results as [(id, score)]
+ batch: batch id
+ """
+
+ raise NotImplementedError
+
+ def query(self, query, limit):
+ """
+ Executes query against database.
+
+ Args:
+ query: input query
+ limit: maximum number of results to return
+
+ Returns:
+ query results
+ """
+
+ raise NotImplementedError
+
+ def execute(self, function, *args):
+ """
+ Executes a user query. This method has common error handling logic.
+
+ Args:
+ function: database execute function
+ args: function arguments
+
+ Returns:
+ result of function(args)
+ """
+
+ try:
+ # Debug log SQL
+ logger.debug(*args)
+
+ return function(*args)
+ except Exception as ex:
+ raise SQLException(ex) from None
diff --git a/src/python/txtai/database/factory.py b/src/python/txtai/database/factory.py
new file mode 100644
index 00000000..a04fafef
--- /dev/null
+++ b/src/python/txtai/database/factory.py
@@ -0,0 +1,42 @@
+"""
+Factory module
+"""
+
+from .sqlite import SQLite
+
+
+class DatabaseFactory:
+ """
+ Methods to create document databases.
+ """
+
+ @staticmethod
+ def create(config):
+ """
+ Create a Database.
+
+ Args:
+ config: database configuration parameters
+
+ Returns:
+ Database
+ """
+
+ # Database instance
+ database = None
+
+ # Enables document database
+ content = config.get("content")
+
+ # Standardize content name
+ if content is True:
+ content = "sqlite"
+
+ # Create document database instance
+ if content == "sqlite":
+ database = SQLite(config)
+
+ # Store config back
+ config["content"] = content
+
+ return database
diff --git a/src/python/txtai/database/sql/__init__.py b/src/python/txtai/database/sql/__init__.py
new file mode 100644
index 00000000..17a0f71f
--- /dev/null
+++ b/src/python/txtai/database/sql/__init__.py
@@ -0,0 +1,6 @@
+"""
+SQL imports
+"""
+
+from .base import SQL, SQLException
+from .expression import Expression
diff --git a/src/python/txtai/database/sql/base.py b/src/python/txtai/database/sql/base.py
new file mode 100644
index 00000000..b3df51c1
--- /dev/null
+++ b/src/python/txtai/database/sql/base.py
@@ -0,0 +1,145 @@
+"""
+SQL module
+"""
+
+from io import StringIO
+from shlex import shlex
+
+from .expression import Expression
+
+
+class SQL:
+ """
+ Translates txtai SQL statements into database native queries.
+ """
+
+ # List of clauses to parse
+ CLAUSES = ["select", "from", "where", "group", "having", "order", "limit"]
+
+ def __init__(self, database):
+ """
+ Creates a new SQL query parser.
+
+ Args:
+ database: database instance that provides resolver callback
+ """
+
+ # Expression parser
+ self.expression = Expression(database.resolve)
+
+ def __call__(self, query):
+ """
+ Parses an input SQL query and normalizes column names in the query clauses. This method will also embed
+ similarity search placeholders into the query.
+
+ Args:
+ query: input query
+
+ Returns:
+ {clause name: clause text}
+ """
+
+ clauses = None
+ if self.issql(query):
+ # Ignore multiple statements
+ query = query.split(";")[0]
+
+ # Tokenize query
+ tokens, positions = self.tokenize(query)
+
+ # Similar queries
+ similar = []
+
+ # Parse SQL clauses
+ clauses = {
+ "select": self.parse(tokens, positions, "select", alias=True),
+ "where": self.parse(tokens, positions, "where", similar=similar),
+ "groupby": self.parse(tokens, positions, "group", offset=2),
+ "having": self.parse(tokens, positions, "having"),
+ "orderby": self.parse(tokens, positions, "order", offset=2),
+ "limit": self.parse(tokens, positions, "limit"),
+ }
+
+ # Add parsed similar queries, if any
+ if similar:
+ clauses["similar"] = similar
+
+ # Return clauses, default to full query if this is not a SQL query
+ return clauses if clauses else {"similar": [[query]]}
+
+ def issql(self, query):
+ """
+ Detects if this is a SQL query.
+
+ Args:
+ query: input query
+
+ Returns:
+ True if this is a valid SQL query, False otherwise
+ """
+
+ query = query.lower()
+ return query.startswith("select ") and (" from txtai " in query or query.endswith(" from txtai"))
+
+ def tokenize(self, query):
+ """
+ Tokenizes SQL query into tokens.
+
+ Args:
+ query: input query
+
+ Returns:
+ (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="=!<>+-*/%"))
+
+ # Identify sql clause token positions
+ positions = {}
+
+ # Get position of clause keywords. For multi-term clauses, validate next token(s) match as well
+ for x, token in enumerate(tokens):
+ t = token.lower()
+ if t not in positions and t in SQL.CLAUSES and (t not in ["group", "order"] or (x + 1 < len(tokens) and tokens[x + 1] == "by")):
+ positions[t] = x
+
+ return (tokens, positions)
+
+ def parse(self, tokens, positions, name, offset=1, alias=False, similar=None):
+ """
+ Runs query column name to database column name mappings for clauses. This method will also
+ parse SIMILAR() function calls, extract parameters for those calls and leave a placeholder
+ to be filled in with similarity results.
+
+ Args:
+ tokens: query tokens
+ positions: token positions - used to locate the start of sql clauses
+ name: current query clause name
+ offset: how many tokens are in the clause name
+ alias: True if terms in the clause should be aliased (i.e. column as alias)
+ similar: list where parsed similar clauses should be stored
+
+ Returns:
+ formatted clause
+ """
+
+ clause = None
+ if name in positions:
+ # Find the next clause token
+ end = [positions.get(x, len(tokens)) for x in SQL.CLAUSES[SQL.CLAUSES.index(name) + 1 :]]
+ end = min(end) if end else len(tokens)
+
+ # Start after current clause token and end before next clause or end of string
+ clause = tokens[positions[name] + offset : end]
+
+ # Parse and resolve parameters
+ clause = self.expression(clause, alias, similar)
+
+ return clause
+
+
+class SQLException(Exception):
+ """
+ Raised for exceptions generated by user SQL queries
+ """
diff --git a/src/python/txtai/database/sql/expression.py b/src/python/txtai/database/sql/expression.py
new file mode 100644
index 00000000..db6d8977
--- /dev/null
+++ b/src/python/txtai/database/sql/expression.py
@@ -0,0 +1,365 @@
+"""
+Expression module
+"""
+
+
+class Expression:
+ """
+ Parses expression statements and runs a set of substitution/formatting rules.
+ """
+
+ # Similar token replacement
+ SIMILAR_TOKEN = "__SIMILAR__"
+
+ # Default list of comparison operators
+ OPERATORS = ["=", "!=", "<>", ">", ">=", "<", "<=", "+", "-", "*", "/", "%", "not", "between", "like", "is", "null"]
+
+ # Default list of logic separators
+ LOGIC_SEPARATORS = ["and", "or"]
+
+ # Default list of sort order operators
+ SORT_ORDER = ["asc", "desc"]
+
+ def __init__(self, resolver):
+ """
+ Creates a new expression parser.
+
+ Args:
+ resolver: function to call to resolve query column names with database column names
+ """
+
+ self.resolver = resolver
+
+ def __call__(self, tokens, alias=False, similar=None):
+ """
+ Parses a list of tokens, replaces query column names with database column names and
+ adds similar query placeholders. Returns rewritten clause.
+
+ Args:
+ tokens: input expression
+ alias: If True, column aliases should be generated
+ similar: list of similar queries, if present new similar queries are appended to this list
+
+ Returns:
+ rewritten clause as a string
+ """
+
+ # Resolve column name tokens
+ tokens = self.resolve(list(tokens), alias, similar)
+
+ # Re-write query and return
+ return self.build(tokens)
+
+ def resolve(self, tokens, alias, similar):
+ """
+ Resolves query column names with database column names.
+
+ Args:
+ tokens: input expression
+ alias: If True, column aliases should be generated
+ similar: list of similar queries, if present new similar queries are appended to this list
+
+ Returns:
+ resolved tokens
+ """
+
+ iterator = enumerate(tokens)
+ for x, token in iterator:
+ # Check if token is a similar function
+ if self.issimilar(tokens, x, similar):
+ # Resolve similar expression
+ self.similar(iterator, tokens, x, similar)
+
+ # Check if token is a function
+ elif self.isfunction(tokens, x):
+ # Resolve function expression
+ self.function(iterator, tokens, token)
+
+ # Check for attribute column not part of a compound expression
+ elif self.iscolumn(token) and not self.isoperator(self.get(tokens, x + 1)):
+ # Resolve attribute expression
+ self.attribute(tokens, x, alias)
+
+ # Check for compound expressions. Need to resolve left and/or right hand side
+ elif self.isoperator(token) and (self.iscolumn(self.get(tokens, x - 1)) or self.iscolumn(self.get(tokens, x + 1))):
+ # Resolve compound expression
+ self.compound(iterator, tokens, x, alias)
+
+ # Remove replaced tokens
+ return [token for token in tokens if token]
+
+ def build(self, tokens):
+ """
+ Builds a new expression from tokens. This method applies a set of rules to generate whitespace between tokens.
+
+ Args:
+ tokens: input expression
+
+ Returns:
+ expression text
+ """
+
+ # Rebuild expression
+ text = ""
+ for token in tokens:
+ # Write token with whitespace rules applied
+ text += self.wrapspace(text, token)
+
+ # Remove any leading/trailing whitespace and return
+ return text.strip()
+
+ def issimilar(self, tokens, x, similar):
+ """
+ Checks if tokens[x] is a similar() function.
+
+ Args:
+ tokens: input tokens
+ x: current position
+ similar: list of similar clauses
+
+ Returns:
+ True if tokens[x] is a similar clause
+ """
+
+ return similar is not None and tokens[x].lower() == "similar" and self.get(tokens, x + 1) == "("
+
+ def similar(self, iterator, tokens, x, similar):
+ """
+ Substitutes a similar() function call with a placeholder that can later be used to add
+ embeddings query results as a filter.
+
+ Args:
+ iterator: tokens iterator
+ tokens: input tokens
+ x: current position
+ similar: list of similar clauses
+ """
+
+ # Get function parameters
+ params = []
+
+ # Clear token from stream, it will be replaced by a placeholder for the function call
+ token = tokens[x]
+ tokens[x] = None
+
+ while token and token != ")":
+ x, token = next(iterator, (None, None))
+ if token and token not in ["(", ",", ")"]:
+ # Strip quotes
+ params.append(token.replace("'", "").replace('"', ""))
+
+ # Clear token from stream
+ tokens[x] = None
+
+ # Add placeholder for embedding similarity results
+ tokens[x] = f"{Expression.SIMILAR_TOKEN}{len(similar)}"
+
+ # Save parameters
+ similar.append(params)
+
+ def isfunction(self, tokens, x):
+ """
+ Checks if tokens[x] is a function.
+
+ Args:
+ tokens: input tokens
+ x: current position
+
+ Returns:
+ True if tokens[x] is a function, False otherwise
+ """
+
+ # Check if token is a functios
+ return not self.isoperator(tokens[x]) and self.get(tokens, x + 1) == "("
+
+ def function(self, iterator, tokens, token):
+ """
+ Resolves column names within the function's parameters.
+
+ Args:
+ iterator: tokens iterator
+ tokens: input tokens
+ token: current token
+ """
+
+ # Consume function parameters
+ while token and token != ")":
+ x, token = next(iterator, (None, None))
+ if self.isfunction(tokens, x):
+ # Resolve function parameters that are functions
+ self.function(iterator, tokens, token)
+ elif self.iscolumn(token):
+ # Resolve function parameter
+ tokens[x] = self.resolver(tokens[x])
+
+ def attribute(self, tokens, x, alias):
+ """
+ Resolves an attribute column name.
+
+ Args:
+ tokens: input tokens
+ x: current token position
+ alias: If True, column aliases should be generated
+ """
+
+ # Alias name
+ name = tokens[x]
+
+ # Resolve attribute expression
+ tokens[x] = self.resolver(tokens[x])
+
+ # Add alias
+ if alias:
+ alias = self.resolver(name, alias=True)
+ tokens[x] += alias if alias else ""
+
+ def compound(self, iterator, tokens, x, alias):
+ """
+ Resolves a compound operator (left side <operator(s)> right side).
+
+ Args:
+ iterator: tokens iterator
+ tokens: input tokens
+ x: current token position
+ alias: If True, column aliases should be generated
+ """
+
+ # Alias name
+ name = None
+
+ # Resolve left side (left side already had function processing applied through standard loop)
+ if self.iscolumn(tokens[x - 1]):
+ name = tokens[x - 1]
+ tokens[x - 1] = self.resolver(tokens[x - 1])
+
+ # Consume operator(s), handle both single and compound operators, i.e. column NOT LIKE 1
+ token = tokens[x]
+ while token and self.isoperator(token):
+ x, token = next(iterator, (None, None))
+
+ # Resolve right side
+ if token and self.iscolumn(token):
+ # Need to process functions since it hasn't went through the standard loop yet
+ if self.isfunction(tokens, x):
+ self.function(iterator, tokens, token)
+ else:
+ name = token
+ tokens[x] = self.resolver(token)
+
+ # Add alias to last token
+ if name and alias:
+ alias = self.resolver(name, alias=True, compound=True)
+ tokens[x] += alias if alias else ""
+
+ def iscolumn(self, token):
+ """
+ Checks if token is a column name.
+
+ Args:
+ token: token to test
+
+ Returns:
+ True if this token is a column name token, False otherwise
+ """
+
+ return token and not self.isoperator(token) and not self.islogicseparator(token) and not self.isliteral(token) and not self.issortorder(token)
+
+ def isoperator(self, token):
+ """
+ Checks if token is an operator token.
+
+ Args:
+ token: token to test
+
+ Returns:
+ True if this token is an operator, False otherwise
+ """
+
+ return token and token.lower() in Expression.OPERATORS
+
+ def islogicseparator(self, token):
+ """
+ Checks if token is a logic separator token.
+
+ Args:
+ token: token to test
+
+ Returns:
+ True if this token is a logic separator, False otherwise
+ """
+
+ return token and token.lower() in Expression.LOGIC_SEPARATORS
+
+ def issortorder(self, token):
+ """
+ Checks if token is a sort order token.
+
+ Args:
+ token: token to test
+
+ Returns:
+ True if this token is a sort order operator, False otherwise
+ """
+
+ return token and token.lower() in Expression.SORT_ORDER
+
+ def isliteral(self, token):
+ """
+ Checks if token is a literal. Literals are wrapped in quotes, parens, wildcards or numeric.
+
+ Args:
+ token: token to test
+
+ Returns:
+ True if this token is a literal, False otherwise
+ """
+
+ return token and (token.startswith(("'", '"', ",", "(", ")", "[", "]", "*")) or token.isnumeric())
+
+ def wrapspace(self, text, token):
+ """
+ Applies whitespace wrapping rules to token.
+
+ Args:
+ text: current text buffer
+ token: token to add
+
+ Returns:
+ token with whitespace rules applied
+ """
+
+ # Wildcards have no whitespace. Need special case since * is also multiply which does have whitespace.
+ if token in ["*"] and (not text or text.endswith((" ", "("))):
+ return token
+
+ # Operator whitespace
+ if self.isoperator(token) or self.islogicseparator(token) or token.lower() in ["in"]:
+ return f" {token} " if not text.endswith(" ") else f"{token} "
+
+ # Comma whitespace
+ if token in [","]:
+ return f"{token} "
+
+ # No whitespace if any of the following is true
+ if not text or text.endswith((" ", "(", "[")) or token in ["(", "[", ")", "]"]:
+ return token
+
+ # Default is to add leading whitespace
+ return f" {token}"
+
+ def get(self, tokens, x):
+ """
+ Gets token at position x. This method will validate position is valid within tokens.
+
+ Args:
+ tokens: input tokens
+ x: position to retrieve
+
+ Returns:
+ tokens[x] if x is a valid position, None otherwise
+ """
+
+ if 0 <= x < len(tokens):
+ return tokens[x]
+
+ return None
diff --git a/src/python/txtai/database/sqlite.py b/src/python/txtai/database/sqlite.py
new file mode 100644
index 00000000..a3d3afbb
--- /dev/null
+++ b/src/python/txtai/database/sqlite.py
@@ -0,0 +1,294 @@
+"""
+SQLite module
+"""
+
+import datetime
+import json
+import sqlite3
+
+from .base import Database
+
+
+class SQLite(Database):
+ """
+ Document database backed by SQLite.
+ """
+
+ # Temporary table for working with id batches
+ CREATE_BATCH = """
+ CREATE TEMP TABLE IF NOT EXISTS batch (
+ id INTEGER,
+ uid TEXT,
+ batch INTEGER
+ )
+ """
+
+ DELETE_BATCH = "DELETE FROM batch"
+ INSERT_BATCH = "INSERT INTO batch VALUES (?, ?, ?)"
+
+ # Temporary table for joining similarity scores
+ CREATE_SCORES = """
+ CREATE TEMP TABLE IF NOT EXISTS scores (
+ id INTEGER,
+ score REAL
+ )
+ """
+
+ DELETE_SCORES = "DELETE FROM scores"
+ INSERT_SCORE = "INSERT INTO scores VALUES (?, ?)"
+
+ # Documents - stores full content
+ CREATE_DOCUMENTS = """
+ CREATE TABLE IF NOT EXISTS documents (
+ uid TEXT PRIMARY KEY,
+ data JSON,
+ tags TEXT,
+ entry DATETIME
+ )
+ """
+
+ INSERT_DOCUMENT = "INSERT INTO documents VALUES (?, ?, ?, ?)"
+ DELETE_DOCUMENTS = "DELETE FROM documents WHERE uid IN (SELECT uid FROM batch)"
+
+ # Sections - stores section text
+ CREATE_SECTIONS = """
+ CREATE TABLE IF NOT EXISTS sections (
+ id INTEGER PRIMARY KEY,
+ uid TEXT,
+ text TEXT,
+ tags TEXT,
+ entry DATETIME
+ )
+ """
+
+ CREATE_SECTIONS_INDEX = "CREATE INDEX section_uid ON sections(uid)"
+ INSERT_SECTION = "INSERT INTO sections VALUES (?, ?, ?, ?, ?)"
+ DELETE_SECTIONS = "DELETE FROM sections WHERE uid IN (SELECT uid FROM batch)"
+
+ # Queries
+ SELECT_IDS = "SELECT id, uid FROM sections WHERE uid in (SELECT uid 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)"
+
+ def __init__(self, config):
+ """
+ Creates a new Database.
+
+ Args:
+ config: database configuration parameters
+ """
+
+ super().__init__(config)
+
+ # SQLite connection handle
+ self.connection = None
+ self.cursor = None
+ self.path = None
+
+ def load(self, path):
+ # Load an existing database
+ self.connection = sqlite3.connect(path)
+ self.cursor = self.connection.cursor()
+ self.path = path
+
+ def insert(self, documents, index=0):
+ # Initialize connection if not open
+ self.initialize()
+
+ # Get entry date
+ entry = datetime.datetime.now()
+
+ # Insert documents
+ for uid, document, tags in documents:
+ if isinstance(document, dict):
+ # Insert document as JSON
+ self.cursor.execute(SQLite.INSERT_DOCUMENT, [uid, json.dumps(document), tags, entry])
+
+ # Extract text, if any
+ document = document.get("text")
+
+ if isinstance(document, list):
+ # Join tokens to text
+ document = " ".join(document)
+
+ if document:
+ # Save text section
+ self.cursor.execute(SQLite.INSERT_SECTION, [index, uid, document, tags, entry])
+ index += 1
+
+ def delete(self, uids):
+ if self.connection:
+ # Batch ids
+ self.batch(uids=uids)
+
+ # Delete all documents and sections by id
+ self.cursor.execute(SQLite.DELETE_DOCUMENTS)
+ self.cursor.execute(SQLite.DELETE_SECTIONS)
+
+ def save(self, path):
+ # Save the changes
+ self.connection.commit()
+
+ # If this is a temporary database, copy over to database at path
+ if not self.path:
+ # Create database
+ connection = sqlite3.connect(path)
+
+ # Copy from existing database to new database
+ self.connection.backup(connection)
+ self.connection.close()
+
+ # Point connection to new database
+ self.connection = connection
+ self.cursor = self.connection.cursor()
+ self.path = path
+
+ def ids(self, uids):
+ # Batch uids and run query
+ self.batch(uids=uids)
+ self.cursor.execute(SQLite.SELECT_IDS)
+
+ # Format and return results
+ return self.cursor.fetchall()
+
+ def query(self, query, limit):
+ # Extract query components
+ select = query.get("select", "*")
+ where = query.get("where")
+ groupby, having = query.get("groupby"), query.get("having")
+ orderby, qlimit = query.get("orderby"), query.get("limit")
+ similarity = query.get("similar")
+
+ # Build query text
+ query = SQLite.TABLE_CLAUSE % select
+ if where is not None:
+ query += f" WHERE {where}"
+ if groupby is not None:
+ query += f" GROUP BY {groupby}"
+ if having is not None:
+ query += f" HAVING {having}"
+ if orderby is not None:
+ query += f" ORDER BY {orderby}"
+
+ # Default ORDER BY if not provided and similarity scores are available
+ if similarity and orderby is None:
+ query += " ORDER BY score DESC"
+
+ # Apply query limit
+ if qlimit is not None or limit:
+ query += f" LIMIT {qlimit if qlimit else limit}"
+
+ # Clear scores when no similar clauses present
+ if not similarity:
+ self.scores(None)
+
+ # Runs a user query through execute method, which has common user query handling logic
+ self.execute(self.cursor.execute, query)
+
+ # Retrieve column list from query
+ columns = [c[0] for c in self.cursor.description]
+
+ # Map results and return
+ results = [{column: row[x] for x, column in enumerate(columns)} for row in self.cursor]
+ return results
+
+ def resolve(self, name, alias=False, compound=False):
+ # Standard column names
+ sections = ["id", "uid", "tags", "entry"]
+ noprefix = ["data", "score", "text"]
+
+ # Alias JSON column expressions
+ if alias:
+ # Only apply aliases to non-standard columns or compound expressions
+ if name not in sections + noprefix or compound:
+ return f' as "{name}"'
+
+ # No alias
+ return None
+
+ # Standard columns - need prefixes
+ if name.lower() in sections:
+ return f"s.{name}"
+
+ # Standard columns - no prefixes
+ if name.lower() in noprefix:
+ return name
+
+ # Other columns come from documents.data JSON
+ return f'json_extract(data, "$.{name}")'
+
+ def embed(self, similarity, batch):
+ # Load similarity results id batch
+ self.batch(ids=[i for i, _ in similarity[batch]], batch=batch)
+
+ # Average and load all similarity scores with first batch
+ if not batch:
+ self.scores(similarity)
+
+ # Return ids clause placeholder
+ return SQLite.IDS_CLAUSE % batch
+
+ def initialize(self):
+ """
+ Creates connection and initial database schema if no connection exists.
+ """
+
+ if not self.connection:
+ # Create temporary database
+ self.connection = sqlite3.connect("")
+ self.cursor = self.connection.cursor()
+
+ # Create initial schema and indices
+ self.cursor.execute(SQLite.CREATE_DOCUMENTS)
+ self.cursor.execute(SQLite.CREATE_SECTIONS)
+ self.cursor.execute(SQLite.CREATE_SECTIONS_INDEX)
+
+ def batch(self, ids=None, uids=None, batch=None):
+ """
+ Loads ids to a temporary batch table for efficient query processing.
+
+ Args:
+ ids: list of ids
+ uids: list of uids
+ batch: batch index, used when statement has multiple subselects
+ """
+
+ # Create or Replace temporary batch table
+ self.cursor.execute(SQLite.CREATE_BATCH)
+
+ # Delete batch when batch id is empty or for batch 0
+ if not batch:
+ self.cursor.execute(SQLite.DELETE_BATCH)
+
+ 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])
+
+ 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)]
+ """
+
+ # Create or Replace temporary scores table
+ self.cursor.execute(SQLite.CREATE_SCORES)
+
+ # Delete scores
+ self.cursor.execute(SQLite.DELETE_SCORES)
+
+ if similarity:
+ # Average scores per id, needed for multiple similar() clauses
+ scores = {}
+ for s in similarity:
+ for i, score in s:
+ if i not in scores:
+ scores[i] = []
+ scores[i].append(score)
+
+ # Average scores by id
+ self.cursor.executemany(SQLite.INSERT_SCORE, [(i, sum(s) / len(s)) for i, s in scores.items()])
diff --git a/src/python/txtai/embeddings/base.py b/src/python/txtai/embeddings/base.py
index 24897b8a..23c602ea 100644
--- a/src/python/txtai/embeddings/base.py
+++ b/src/python/txtai/embeddings/base.py
@@ -9,20 +9,19 @@ import shutil
import numpy as np
from ..ann import ANNFactory
+from ..database import DatabaseFactory
from ..scoring import ScoringFactory
from ..vectors import VectorsFactory
from .reducer import Reducer
+from .search import Search
class Embeddings:
"""
- Model that builds sentence embeddings from a list of tokens.
-
- Optional scoring method can be created to weigh tokens when creating embeddings. Averaging used if no scoring method provided.
-
- The model also applies principal component analysis using a LSA model. This reduces the noise of common but less
- relevant terms.
+ 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
+ that have the same meaning, not necessarily the same keywords.
"""
# pylint: disable = W0231
@@ -37,8 +36,8 @@ class Embeddings:
# Configuration
self.config = config
- # Embeddings model
- self.embeddings = None
+ # Approximate nearest neighbor index
+ self.ann = None
if self.config and self.config.get("method") != "transformers":
# Dimensionality reduction model
@@ -49,15 +48,18 @@ class Embeddings:
else:
self.reducer, self.scoring = None, None
- # Sentence vectors model
- self.model = self.loadVectors() if self.config else None
+ # Sentence vectors model - transforms text to embeddings vectors
+ self.model = self.loadvectors() if self.config else None
+
+ # Document database
+ self.database = None
def score(self, documents):
"""
Builds a scoring index.
Args:
- documents: list of (id, text|tokens, tags)
+ documents: list of (id, dict|text|tokens, tags)
"""
if self.scoring:
@@ -69,7 +71,7 @@ class Embeddings:
Builds an embeddings index. This method overwrites an existing index.
Args:
- documents: list of (id, text|tokens, tags)
+ documents: list of (id, dict|text|tokens, tags)
"""
# Transform documents to embeddings vectors
@@ -83,28 +85,35 @@ class Embeddings:
# Normalize embeddings
self.normalize(embeddings)
- # Save embeddings metadata
- self.config["ids"] = ids
+ # Save index dimensions
self.config["dimensions"] = dimensions
- # Create embeddings index
- self.embeddings = ANNFactory.create(self.config)
+ # Create approximate nearest neighbor index
+ self.ann = ANNFactory.create(self.config)
# Build the index
- self.embeddings.index(embeddings)
+ self.ann.index(embeddings)
+
+ self.database = DatabaseFactory.create(self.config)
+ if self.database:
+ # Add documents to database
+ self.database.insert(documents)
+ else:
+ # Save ids for indices with no database
+ self.config["ids"] = ids
def upsert(self, documents):
"""
- Runs an embeddings index upsert operation. If the index exists, new
- data is appended to the index, existing data is updated. If the index
- doesn't exist, this method runs a standard index operation.
+ Runs an embeddings upsert operation. If the index exists, new data is
+ appended to the index, existing data is updated. If the index doesn't exist,
+ this method runs a standard index operation.
Args:
- documents: list of (id, text|tokens, tags)
+ documents: list of (id, dict|text|tokens, tags)
"""
# Run standard insert if index doesn't exist
- if not self.embeddings:
+ if not self.ann:
self.index(documents)
return
@@ -117,11 +126,18 @@ class Embeddings:
# Delete existing elements
self.delete(ids)
+ # Get offset before it changes
+ offset = self.config.get("offset", 0)
+
# Append elements the index
- self.embeddings.append(embeddings)
+ self.ann.append(embeddings)
- # Save embeddings metadata
- self.config["ids"] = self.config["ids"] + ids
+ if self.database:
+ # Add documents to database
+ self.database.insert(documents, offset)
+ else:
+ # Save ids for indices with no database
+ self.config["ids"] = self.config["ids"] + ids
def delete(self, ids):
"""
@@ -131,7 +147,7 @@ class Embeddings:
ids: list of ids to delete
Returns:
- ids deleted
+ list of ids deleted
"""
# List of internal indices for each candidate id to delete
@@ -140,22 +156,33 @@ class Embeddings:
# List of deleted ids
deletes = []
- # Get handle to config ids
- cids = self.config["ids"]
+ if self.database:
+ # Retrieve id-uid mappings from database
+ ids = self.database.ids(ids)
- # Find existing ids
- for uid in ids:
- indices.extend([index for index, value in enumerate(cids) if uid == value])
+ # Parse out indices and ids to delete
+ indices = [i for i, _ in ids]
+ deletes = list(set(uid for _, uid in ids))
+
+ # Delete ids from database
+ self.database.delete(deletes)
+ else:
+ # Lookup ids from config for indices with no database
+ cids = self.config["ids"]
+
+ # Find existing ids
+ for uid in ids:
+ indices.extend([index for index, value in enumerate(cids) if uid == value])
- # Delete any found from config ids and embeddings
- if indices:
# Clear config ids
for index in indices:
deletes.append(cids[index])
cids[index] = None
+ # Delete indices from ann embeddings
+ if indices:
# Delete ids from index
- self.embeddings.delete(indices)
+ self.ann.delete(indices)
return deletes
@@ -201,53 +228,42 @@ class Embeddings:
Total number of elements in this embeddings index.
Returns:
- number of elements in embeddings index
+ number of elements in this embeddings index
"""
- return self.embeddings.count() if self.embeddings else 0
+ return self.ann.count() if self.ann else 0
def search(self, query, limit=3):
"""
- Finds documents in the embeddings model most similar to the input query. Returns
- a list of (id, score) sorted by highest score, where id is the document id in
- the embeddings model.
+ 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.
Args:
query: query text|tokens
limit: maximum results
Returns:
- list of (id, score)
+ list of (id, score) for ann seach, list of dict for an ann+database search
"""
return self.batchsearch([query], limit)[0]
def batchsearch(self, queries, limit=3):
"""
- Finds documents in the embeddings model most similar to the input queries. Returns
- a list of (id, score) sorted by highest score per query, where id is the document id
- in the embeddings model.
+ 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.
Args:
queries: queries text|tokens
limit: maximum results
Returns:
- list of (id, score) per query
+ list of (id, score) per query for ann search, list of dict per query for an ann+database search
"""
- # Convert queries to embedding vectors
- embeddings = np.array([self.transform((None, query, None)) for query in queries])
-
- # Search embeddings index
- results = self.embeddings.search(embeddings, limit)
-
- # Map ids if id mapping available
- lookup = self.config.get("ids")
- if lookup:
- results = [[(lookup[i], score) for i, score in r] for r in results]
-
- return results
+ return Search(self)(queries, limit)
def similarity(self, query, texts):
"""
@@ -289,14 +305,7 @@ class Embeddings:
def load(self, path):
"""
- Loads a pre-trained model.
-
- Models have the following files:
- config - configuration
- embeddings - sentence embeddings index
- lsa - LSA model, used to remove the principal component(s)
- scoring - scoring model used to weigh word vectors
- vectors - vectors model
+ Loads an existing index from path.
Args:
path: input directory path
@@ -310,23 +319,27 @@ class Embeddings:
if self.config.get("storevectors"):
self.config["path"] = os.path.join(path, self.config["path"])
- # Sentence embeddings index
- self.embeddings = ANNFactory.create(self.config)
- self.embeddings.load(f"{path}/embeddings")
+ # Approximate nearest neighbor index - stores embeddings vectors
+ self.ann = ANNFactory.create(self.config)
+ self.ann.load(f"{path}/embeddings")
- # Dimensionality reduction
+ # Dimensionality reduction model (word vectors only)
if self.config.get("pca"):
- with open(f"{path}/lsa", "rb") as handle:
- self.reducer = Reducer()
- self.reducer.load(path)
+ self.reducer = Reducer()
+ self.reducer.load(f"{path}/lsa")
- # Embedding scoring
+ # Embedding scoring model (word vectors only)
if self.config.get("scoring"):
self.scoring = ScoringFactory.create(self.config["scoring"])
- self.scoring.load(path)
+ self.scoring.load(f"{path}/scoring")
- # Sentence vectors model - transforms text into sentence embeddings
- self.model = self.loadVectors()
+ # Sentence vectors model - transforms text to embeddings vectors
+ self.model = self.loadvectors()
+
+ # Document database - stores document content
+ self.database = DatabaseFactory.create(self.config)
+ if self.database:
+ self.database.load(f"{path}/documents")
def exists(self, path):
"""
@@ -353,7 +366,7 @@ class Embeddings:
# Create output directory, if necessary
os.makedirs(path, exist_ok=True)
- # Copy vectors file
+ # Copy sentence vectors model
if self.config.get("storevectors"):
shutil.copyfile(self.config["path"], os.path.join(path, os.path.basename(self.config["path"])))
@@ -363,18 +376,22 @@ class Embeddings:
with open(f"{path}/config", "wb") as handle:
pickle.dump(self.config, handle, protocol=pickle.HIGHEST_PROTOCOL)
- # Write sentence embeddings index
- self.embeddings.save(f"{path}/embeddings")
+ # Save approximate nearest neighbor index
+ self.ann.save(f"{path}/embeddings")
- # Save dimensionality reduction
+ # Save dimensionality reduction model (word vectors only)
if self.reducer:
- self.reducer.save(path)
+ self.reducer.save(f"{path}/lsa")
- # Save embedding scoring
+ # Save embedding scoring model (word vectors only)
if self.scoring:
- self.scoring.save(path)
+ self.scoring.save(f"{path}/scoring")
+
+ # Save document database
+ if self.database:
+ self.database.save(f"{path}/documents")
- def loadVectors(self):
+ def loadvectors(self):
"""
Loads a vector model set in config.
@@ -389,14 +406,14 @@ class Embeddings:
Transforms documents into embeddings vectors.
Args:
- documents: list of (id, text|tokens, tags)
+ documents: list of (id, dict|text|tokens, tags)
Returns:
- tuple of document ids, dimensions and embeddings
+ (document ids, dimensions, embeddings)
"""
# Transform documents to embeddings vectors
- ids, dimensions, stream = self.model.index(documents)
+ ids, dimensions, stream = self.model.index(self.hastext(documents))
# Load streamed embeddings back to memory
embeddings = np.empty((len(ids), dimensions), dtype=np.float32)
@@ -422,3 +439,25 @@ class Embeddings:
embeddings /= np.linalg.norm(embeddings, axis=1)[:, np.newaxis]
else:
embeddings /= np.linalg.norm(embeddings)
+
+ def hastext(self, documents):
+ """
+ Selects documents that have text to vectorize for similarity indexing.
+
+ Must be one of the following:
+ - text
+ - list of text tokens
+ - dict with the field "text"
+
+ Args:
+ documents: list of (id, dict|text|tokens, tags)
+
+ Returns:
+ filtered documents
+ """
+
+ for document in documents:
+ if isinstance(document[1], (str, list)):
+ yield document
+ elif isinstance(document[1], dict) and "text" in document[1]:
+ yield (document[0], document[1]["text"], document[2])
diff --git a/src/python/txtai/embeddings/search.py b/src/python/txtai/embeddings/search.py
new file mode 100644
index 00000000..0a157e45
--- /dev/null
+++ b/src/python/txtai/embeddings/search.py
@@ -0,0 +1,145 @@
+"""
+Search module
+"""
+
+import numpy as np
+
+
+class Search:
+ """
+ Executes a batch search action. A search can be both approximate nearest neighbor and/or database driven.
+ """
+
+ def __init__(self, embeddings):
+ """
+ Creates a new search.
+
+ Args:
+ embeddings: embeddings instance
+ """
+
+ self.embeddings = embeddings
+
+ # Alias embeddings attributes
+ self.config = embeddings.config
+ self.ann = embeddings.ann
+ self.database = embeddings.database
+ self.transform = embeddings.transform
+
+ def __call__(self, queries, limit):
+ """
+ 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.
+
+ Args:
+ queries: list of queries
+ limit: maximum results
+
+ Returns:
+ list of (id, score) per query for ann search, list of dict per query for an ann+database search
+ """
+
+ if self.database:
+ return self.dbsearch(queries, limit)
+
+ # Default: execute an approximate nearest neighbor search
+ return self.search(queries, limit)
+
+ def search(self, queries, limit):
+ """
+ Executes an approximate nearest neighbor search.
+
+ Args:
+ queries: list of queries
+ limit: maximum results
+
+ Returns:
+ list of (id, score) per query
+ """
+
+ # Convert queries to embedding vectors
+ embeddings = np.array([self.transform((None, query, None)) for query in queries])
+
+ # Search approximate nearest neighbor index
+ results = self.ann.search(embeddings, limit)
+
+ # 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
+ if "ids" in self.config:
+ lookup = self.config["ids"]
+ return [[(lookup[i], score) for i, score in r] for r in results]
+
+ return results
+
+ def dbsearch(self, queries, limit):
+ """
+ Executes an approximate nearest neighbor + database search.
+
+ Args:
+ queries: list of queries
+ limit: maximum results
+
+ Returns:
+ list of dict per query
+ """
+
+ # Parse queries
+ queries = [self.database.parse(query) for query in queries]
+
+ # Override limit with query limit, if applicable
+ limit = max(limit, self.limit(queries))
+
+ # Extract embeddings queries as single batch across all queries
+ equeries, search, window = [], [], 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 text argument (first argument)
+ equeries.append((x, params[0]))
+
+ # Second argument is similarity candidate window
+ if len(params) > 1 and params[1].isnumeric():
+ # Get largest window value across all queries
+ window = int(params[1]) if int(params[1]) > window else window
+
+ # Bulk approximate nearest neighbor search
+ if equeries:
+ search = self.search([query for _, query in equeries], limit * 10 if not window else window)
+
+ # Combine approximate nearest neighbor 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)
+ results.append(result)
+
+ return results
+
+ def limit(self, queries):
+ """
+ Parses the largest LIMIT clause from queries.
+
+ Args:
+ queries: list of queries
+
+ Returns:
+ largest limit number or 0 if not found
+ """
+
+ # Override limit with largest limit from database queries
+ qlimit = 0
+ for query in queries:
+ # Parse out qlimit
+ l = query.get("limit")
+ if l and l.isnumeric():
+ l = int(l)
+
+ qlimit = l if l and l > qlimit else qlimit
+
+ return qlimit
diff --git a/test/python/testdatabase/__init__.py b/test/python/testdatabase/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/test/python/testdatabase/testembeddings.py b/test/python/testdatabase/testembeddings.py
new file mode 100644
index 00000000..ea37b2c2
--- /dev/null
+++ b/test/python/testdatabase/testembeddings.py
@@ -0,0 +1,217 @@
+"""
+Embeddings+database module tests
+"""
+
+import os
+import tempfile
+import unittest
+
+from txtai.embeddings import Embeddings
+from txtai.database import Database, SQLException
+from txtai.vectors import WordVectors
+
+
+class TestEmbeddings(unittest.TestCase):
+ """
+ Embeddings with a database tests
+ """
+
+ @classmethod
+ def setUpClass(cls):
+ """
+ Initialize test data.
+ """
+
+ cls.data = [
+ "US tops 5 million confirmed virus cases",
+ "Canada's last fully intact ice shelf has suddenly collapsed, forming a Manhattan-sized iceberg",
+ "Beijing mobilises invasion craft along coast as Taiwan tensions escalate",
+ "The National Park Service warns against sacrificing slower friends in a bear attack",
+ "Maine man wins $1M from $25 lottery ticket",
+ "Make huge profits without work, earn up to $100,000 a day",
+ ]
+
+ # Create embeddings model, backed by sentence-transformers & transformers
+ cls.embeddings = Embeddings({"path": "sentence-transformers/nli-mpnet-base-v2", "content": True})
+
+ def testData(self):
+ """
+ Test content storage and retrieval
+ """
+
+ data = self.data + [{"date": "2021-01-01", "text": "Baby panda", "flag": 1}]
+
+ # Create an index for the list of text
+ self.embeddings.index([(uid, text, None) for uid, text in enumerate(data)])
+
+ # Search for best match
+ result = self.embeddings.search("feel good story", 1)[0]
+ self.assertEqual(result["text"], data[-1]["text"])
+
+ def testDelete(self):
+ """
+ Test delete
+ """
+
+ # Create an index for the list of text
+ self.embeddings.index([(uid, text, None) for uid, text in enumerate(self.data)])
+
+ # Delete best match
+ self.embeddings.delete([4])
+
+ # Search for best match
+ result = self.embeddings.search("feel good story", 1)[0]
+
+ self.assertEqual(self.embeddings.count(), 5)
+ self.assertEqual(result["text"], self.data[5])
+
+ def testIndex(self):
+ """
+ Test index
+ """
+
+ # Create an index for the list of text
+ self.embeddings.index([(uid, text, None) for uid, text in enumerate(self.data)])
+
+ # Search for best match
+ result = self.embeddings.search("feel good story", 1)[0]
+
+ self.assertEqual(result["text"], self.data[4])
+
+ def testNotImplemented(self):
+ """
+ Tests exceptions for non-implemented methods
+ """
+
+ database = Database({})
+
+ self.assertRaises(NotImplementedError, database.load, None)
+ self.assertRaises(NotImplementedError, database.insert, None)
+ self.assertRaises(NotImplementedError, database.delete, None)
+ self.assertRaises(NotImplementedError, database.save, None)
+ self.assertRaises(NotImplementedError, database.ids, None)
+ self.assertRaises(NotImplementedError, database.resolve, None, None)
+ self.assertRaises(NotImplementedError, database.embed, None, None)
+ self.assertRaises(NotImplementedError, database.query, None, None)
+
+ def testSave(self):
+ """
+ Test save
+ """
+
+ # Create an index for the list of text
+ self.embeddings.index([(uid, text, None) for uid, text in enumerate(self.data)])
+
+ # Generate temp file path
+ index = os.path.join(tempfile.gettempdir(), "embeddings")
+
+ self.embeddings.save(index)
+ self.embeddings.load(index)
+
+ # Search for best match
+ result = self.embeddings.search("feel good story", 1)[0]
+
+ self.assertEqual(result["text"], self.data[4])
+
+ # Test offsets still work after save/load
+ self.embeddings.upsert([(0, "Test insert", None)])
+ self.assertEqual(self.embeddings.count(), len(self.data))
+
+ def testSQL(self):
+ """
+ Test running a SQL query
+ """
+
+ # Create an index for the list of text
+ self.embeddings.index([(uid, text, None) for uid, text in enumerate(self.data)])
+
+ # Test similar
+ result = self.embeddings.search(
+ "select * from txtai where similar('feel good story') group by text having count(*) > 0 order by score desc", 5
+ )[0]
+ self.assertEqual(result["text"], self.data[4])
+
+ # Test where
+ result = self.embeddings.search("select * from txtai where text like '%iceberg%'", 1)[0]
+ self.assertEqual(result["text"], self.data[1])
+
+ # Test count
+ result = self.embeddings.search("select count(*) from txtai")[0]
+ self.assertEqual(list(result.values())[0], len(self.data))
+
+ # Test columns
+ result = self.embeddings.search("select id, text, data, entry from txtai")[0]
+ self.assertEqual(sorted(result.keys()), ["data", "entry", "id", "text"])
+
+ # Test SQL parse error
+ with self.assertRaises(SQLException):
+ self.embeddings.search("select * from txtai where bad,query")
+
+ def testUpsert(self):
+ """
+ Test upsert
+ """
+
+ # Build data array
+ data = [(uid, text, None) for uid, text in enumerate(self.data)]
+
+ # Reset embeddings for test
+ self.embeddings.ann = None
+
+ # Create an index for the list of text
+ self.embeddings.upsert(data)
+
+ # Update data
+ data[0] = (0, "Feel good story: baby panda born", None)
+ self.embeddings.upsert([data[0]])
+
+ # Search for best match
+ result = self.embeddings.search("feel good story", 1)[0]
+
+ self.assertEqual(result["text"], data[0][1])
+
+ def testWords(self):
+ """
+ Test embeddings backed by word vectors
+ """
+
+ # Initialize model path
+ path = os.path.join(tempfile.gettempdir(), "model")
+ os.makedirs(path, exist_ok=True)
+
+ # Build tokens file
+ with tempfile.NamedTemporaryFile(mode="w", delete=False) as output:
+ tokens = output.name
+ for x in self.data:
+ output.write(x + "\n")
+
+ # Word vectors path
+ vectors = os.path.join(path, "test-10d")
+
+ # Build word vectors, if they don't already exist
+ WordVectors.build(tokens, 10, 1, vectors)
+
+ # Create dataset
+ data = [(x, row, None) for x, row in enumerate(self.data)]
+
+ # Create embeddings model, backed by word vectors
+ embeddings = Embeddings(
+ {"path": vectors + ".magnitude", "storevectors": True, "scoring": "bm25", "pca": 3, "quantize": True, "content": True}
+ )
+
+ # Call scoring and index methods
+ embeddings.score(data)
+ embeddings.index(data)
+
+ # Test search
+ self.assertIsNotNone(embeddings.search("win", 1))
+
+ # Generate temp file path
+ index = os.path.join(tempfile.gettempdir(), "wembeddings")
+
+ # Test save/load
+ embeddings.save(index)
+ embeddings.load(index)
+
+ # Test search
+ self.assertIsNotNone(embeddings.search("win", 1))
diff --git a/test/python/testdatabase/testsql.py b/test/python/testdatabase/testsql.py
new file mode 100644
index 00000000..c2723376
--- /dev/null
+++ b/test/python/testdatabase/testsql.py
@@ -0,0 +1,179 @@
+"""
+SQL module tests
+"""
+
+import unittest
+
+from txtai.database import SQL, SQLException, SQLite
+
+
+class TestSQL(unittest.TestCase):
+ """
+ Tests SQL parsing and generation.
+ """
+
+ @classmethod
+ def setUpClass(cls):
+ """
+ Initialize test data.
+ """
+
+ # Create SQL parser for SQLite
+ cls.db = SQLite({})
+ cls.db.initialize()
+
+ cls.sql = SQL(cls.db)
+
+ def testBadSQL(self):
+ """
+ Test invalid SQL
+ """
+
+ with self.assertRaises(SQLException):
+ self.db.search("select * from txtai where order by")
+
+ with self.assertRaises(SQLException):
+ self.db.search("select * from txtai where groupby order by")
+
+ with self.assertRaises(SQLException):
+ self.db.search("select * from txtai where a(1)")
+
+ with self.assertRaises(SQLException):
+ self.db.search("select a b c from txtai where id match id")
+
+ def testGroupby(self):
+ """
+ Test group by clauses
+ """
+
+ prefix = "select count(*), flag from txtai "
+
+ self.assertSql("groupby", prefix + "group by text", "text")
+ self.assertSql("groupby", prefix + "group by distinct(a)", 'distinct(json_extract(data, "$.a"))')
+ self.assertSql("groupby", prefix + "where a > 1 group by text", "text")
+
+ def testHaving(self):
+ """
+ Test having clauses
+ """
+
+ prefix = "select count(*), flag from txtai "
+
+ self.assertSql("having", prefix + "group by text having count(*) > 1", "count(*) > 1")
+ self.assertSql("having", prefix + "where flag = 1 group by text having count(*) > 1", "count(*) > 1")
+
+ def testLimit(self):
+ """
+ Test limit clauses
+ """
+
+ prefix = "select count(*) from txtai "
+
+ self.assertSql("limit", prefix + "limit 100", "100")
+
+ def testOrderby(self):
+ """
+ Test order by clauses
+ """
+
+ prefix = "select * from txtai "
+
+ self.assertSql("orderby", prefix + "order by id", "s.id")
+ self.assertSql("orderby", prefix + "order by id, text", "s.id, text")
+ self.assertSql("orderby", prefix + "order by id asc", "s.id asc")
+ self.assertSql("orderby", prefix + "order by id desc", "s.id desc")
+ self.assertSql("orderby", prefix + "order by id asc, text desc", "s.id asc, text desc")
+
+ def testSelectBasic(self):
+ """
+ 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', [id], (id) from txtai", "'id', [s.id], (s.id)")
+ self.assertSql("select", "select * from txtai", "*")
+
+ def testSelectCompound(self):
+ """
+ Test compound select clauses
+ """
+
+ self.assertSql("select", "select a + 1 from txtai", 'json_extract(data, "$.a") + 1 as "a"')
+ self.assertSql("select", "select 1 * a from txtai", '1 * json_extract(data, "$.a") as "a"')
+ self.assertSql("select", "select a/1 from txtai", 'json_extract(data, "$.a") / 1 as "a"')
+ self.assertSql("select", "select avg(a-b) from txtai", 'avg(json_extract(data, "$.a") - json_extract(data, "$.b"))')
+ self.assertSql("select", "select distinct(text) from txtai", "distinct(text)")
+ self.assertSql("select", "select id, score, (a/2)*3 from txtai", 's.id, score, (json_extract(data, "$.a") / 2) * 3')
+
+ def testWhereBasic(self):
+ """
+ Test basic where clauses
+ """
+
+ prefix = "select * from txtai "
+
+ self.assertSql("where", prefix + "where a = b", 'json_extract(data, "$.a") = json_extract(data, "$.b")')
+ self.assertSql("where", prefix + "where a = b.value", 'json_extract(data, "$.a") = json_extract(data, "$.b.value")')
+ self.assertSql("where", prefix + "where a = 1", 'json_extract(data, "$.a") = 1')
+ self.assertSql("where", prefix + "WHERE 1 = a", '1 = json_extract(data, "$.a")')
+ self.assertSql("where", prefix + "WHERE a LIKE 'abc'", "json_extract(data, \"$.a\") LIKE 'abc'")
+ 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')
+
+ def testWhereCompound(self):
+ """
+ Test compound where clauses
+ """
+
+ prefix = "select * from txtai "
+
+ self.assertSql("where", prefix + "where a > (b + 1)", 'json_extract(data, "$.a") > (json_extract(data, "$.b") + 1)')
+ self.assertSql("where", prefix + "where a > func('abc')", "json_extract(data, \"$.a\") > func('abc')")
+ self.assertSql(
+ "where", prefix + "where (id = 1 or id = 2) and a like 'abc'", "(s.id = 1 or s.id = 2) and json_extract(data, \"$.a\") like 'abc'"
+ )
+ self.assertSql(
+ "where",
+ 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 f(id) = b(id)", "f(s.id) = b(s.id)")
+ self.assertSql("where", prefix + "WHERE f(id)", "f(s.id)")
+
+ def testWhereSimilar(self):
+ """
+ Test similar functions
+ """
+
+ prefix = "select * from txtai "
+
+ self.assertSql("where", prefix + "where similar('abc')", "__SIMILAR__0")
+ self.assertSql("similar", prefix + "where similar('abc')", [["abc"]])
+
+ self.assertSql("where", prefix + "where similar('abc') AND id = 1", "__SIMILAR__0 AND s.id = 1")
+ self.assertSql("similar", prefix + "where similar('abc')", [["abc"]])
+
+ self.assertSql("where", prefix + "where similar('abc') and similar('def')", "__SIMILAR__0 and __SIMILAR__1")
+ self.assertSql("similar", prefix + "where similar('abc') and similar('def')", [["abc"], ["def"]])
+
+ self.assertSql("where", prefix + "where similar('abc', 1000)", "__SIMILAR__0")
+ self.assertSql("similar", prefix + "where similar('abc', 1000)", [["abc", "1000"]])
+
+ self.assertSql("where", prefix + "where similar('abc', 1000) and similar('def', 10)", "__SIMILAR__0 and __SIMILAR__1")
+ self.assertSql("similar", prefix + "where similar('abc', 1000) and similar('def', 10)", [["abc", "1000"], ["def", "10"]])
+
+ def assertSql(self, clause, query, expected):
+ """
+ Helper method to assert a query clause is as expected
+
+ Args:
+ clause: clause to select
+ query: input query
+ expected: expected transformed query value
+ """
+
+ self.assertEqual(self.sql(query)[clause], expected)
diff --git a/test/python/testembeddings.py b/test/python/testembeddings.py
index 690d46b9..0de05932 100644
--- a/test/python/testembeddings.py
+++ b/test/python/testembeddings.py
@@ -105,7 +105,7 @@ class TestEmbeddings(unittest.TestCase):
data = [(uid, text, None) for uid, text in enumerate(self.data)]
# Reset embeddings for test
- self.embeddings.embeddings = None
+ self.embeddings.ann = None
# Create an index for the list of text
self.embeddings.upsert(data)