💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows
Python agentsaiai-agentsembeddingsinformation-retrievallanguage-modellarge-language-modelsllmnlppythonragretrieval-augmented-generationsearchsearch-enginesemantic-searchsentence-embeddingstransformerstxtaivector-databasevector-search
Add similar query clause to graph queries, closes #875
davidmezzettia92bb73c9c46
diff --git a/src/python/txtai/embeddings/search/base.py b/src/python/txtai/embeddings/search/base.pyindex abb02ec2..e3c040bf 100644--- a/src/python/txtai/embeddings/search/base.py+++ b/src/python/txtai/embeddings/search/base.py@@ -72,7 +72,7 @@ class Search:# Graph searchif self.graph and self.graph.isquery(queries):- return self.graph.batchsearch(queries, limit, self.indexids)+ return self.graphsearch(queries, limit, weights, index)# Database searchif not self.indexonly and self.database:@@ -306,3 +306,33 @@ class Search:qlimit = l if l and l > qlimit else qlimitreturn qlimit++ def graphsearch(self, queries, limit, weights, index):+ """+ Executes an index + graph search.++ Args:+ queries: list of queries+ limit: maximum results+ weights: default hybrid score weights+ index: default index name++ Returns:+ graph search results+ """++ # Parse queries+ queries = [self.graph.parse(query) for query in queries]++ # Override limit with query limit, if applicable+ limit = max(limit, self.limit(queries))++ # Bulk index scan+ scan = Scan(self.search, limit, weights, index)(queries, None)++ # Combine index search results with database search results+ for x, query in enumerate(queries):+ # Add search results to query+ query["results"] = [r for y, r in scan if x == y]++ return self.graph.batchsearch(queries, limit, self.indexids)diff --git a/src/python/txtai/graph/__init__.py b/src/python/txtai/graph/__init__.pyindex 773bb66a..1b0b3fbe 100644--- a/src/python/txtai/graph/__init__.py+++ b/src/python/txtai/graph/__init__.py@@ -5,5 +5,6 @@ Graph importsfrom .base import Graphfrom .factory import GraphFactoryfrom .networkx import NetworkX+from .query import Queryfrom .rdbms import RDBMSfrom .topics import Topicsdiff --git a/src/python/txtai/graph/base.py b/src/python/txtai/graph/base.pyindex 2e821464..30449d9d 100644--- a/src/python/txtai/graph/base.py+++ b/src/python/txtai/graph/base.py@@ -266,23 +266,33 @@ class Graph:raise NotImplementedError- def search(self, query, limit=None, graph=False):+ def isquery(self, queries):"""- Searches graph for nodes matching query.+ Checks if queries are supported graph queries.++ Args:+ queries: queries to check++ Returns:+ True if all the queries are supported graph queries, False otherwise+ """++ raise NotImplementedError++ def parse(self, query):+ """+ Parses a graph query into query components.Args:query: graph query- limit: maximum results- graph: return graph results if TrueReturns:- list of dict if graph is set to False- filtered graph if graph is set to True+ query components as a dictionary"""raise NotImplementedError- def batchsearch(self, queries, limit=None, graph=False):+ def search(self, query, limit=None, graph=False):"""Searches graph for nodes matching query.@@ -292,23 +302,27 @@ class Graph:graph: return graph results if TrueReturns:- list of dict+ list of dict if graph is set to False+ filtered graph if graph is set to True"""- return [self.search(query, limit, graph) for query in queries]+ raise NotImplementedError- def isquery(self, queries):+ def batchsearch(self, queries, limit=None, graph=False):"""- Checks if queries are supported graph queries.+ Searches graph for nodes matching query.Args:- queries: queries to check+ query: graph query+ limit: maximum results+ graph: return graph results if TrueReturns:- True if all the queries are supported graph queries, False otherwise+ list of dict if graph is set to False+ filtered graph if graph is set to True"""- raise NotImplementedError+ return [self.search(query, limit, graph) for query in queries]def communities(self, config):"""diff --git a/src/python/txtai/graph/networkx.py b/src/python/txtai/graph/networkx.pyindex 1aa7cde4..9076030d 100644--- a/src/python/txtai/graph/networkx.py+++ b/src/python/txtai/graph/networkx.py@@ -10,7 +10,6 @@ from tempfile import TemporaryDirectorytry:import networkx as nx- from grandcypher import GrandCypherfrom networkx.algorithms.community import asyn_lpa_communities, greedy_modularity_communities, louvain_partitionsfrom networkx.readwrite import json_graph@@ -22,6 +21,7 @@ from ..archive import ArchiveFactoryfrom ..serialize import SerializeError, SerializeFactoryfrom .base import Graph+from .query import Query# pylint: disable=R0904@@ -114,9 +114,15 @@ class NetworkX(Graph):# pylint: disable=E1121return nx.shortest_path(self.backend, source, target, self.distance)+ def isquery(self, queries):+ return Query().isquery(queries)++ def parse(self, query):+ return Query().parse(query)+def search(self, query, limit=None, graph=False):- # Run openCypher query- results = GrandCypher(self.backend, limit if limit else 3).run(query)+ # Run graph query+ results = Query()(self, query, limit)# Transform into filtered graphif graph:@@ -141,10 +147,6 @@ class NetworkX(Graph):return rows- def isquery(self, queries):- # Check for required graph query clauses- return all(query and query.strip().startswith("MATCH ") and "RETURN " in query for query in queries)-def communities(self, config):# Get community detection algorithmalgorithm = config.get("algorithm")diff --git a/src/python/txtai/graph/query.py b/src/python/txtai/graph/query.pynew file mode 100644index 00000000..219f07b4--- /dev/null+++ b/src/python/txtai/graph/query.py@@ -0,0 +1,181 @@+"""+Query module+"""++import logging+import re++try:+ from grandcypher import GrandCypher++ GRANDCYPHER = True+except ImportError:+ GRANDCYPHER = False++# Logging configuration+logger = logging.getLogger(__name__)+++class Query:+ """+ Runs openCypher graph queries using the GrandCypher library. This class also supports search functions.+ """++ # Similar token+ SIMILAR = "__SIMILAR__"++ def __init__(self):+ """+ Create a new graph query instance.+ """++ if not GRANDCYPHER:+ raise ImportError('GrandCypher is not available - install "graph" extra to enable')++ def __call__(self, graph, query, limit):+ """+ Runs a graph query.++ Args:+ graph: graph instance+ query: graph query, can be a full query string or a parsed query dictionary+ limit: number of results++ Returns:+ results+ """++ # Results by attribute and ids filter+ attributes, uids = None, None++ # Build the query from a parsed query+ if isinstance(query, dict):+ query, attributes, uids = self.build(query)++ # Filter graph, if applicable+ if uids:+ graph = self.filter(graph, attributes, uids)++ # Debug log graph query+ logger.debug(query)++ # Run openCypher query+ return GrandCypher(graph.backend, limit if limit else 3).run(query)++ def isquery(self, queries):+ """+ Checks a list of queries to see if all queries are openCypher queries.++ Args:+ queries: list of queries to check++ Returns:+ True if all queries are openCypher queries+ """++ # Check for required graph query clauses+ return all(query and query.strip().startswith("MATCH ") and "RETURN " in query for query in queries)++ def parse(self, query):+ """+ Parses a graph query. This method supports parsing search functions and replacing them with placeholders.++ Args:+ query: graph query++ Returns:+ parsed query as a dictionary+ """++ # Parameters+ where, limit, nodes, similar = None, None, [], []++ # Parse where clause+ match = re.search(r"where(.+?)return", query, flags=re.DOTALL | re.IGNORECASE)+ if match:+ where = match.group(1).strip()++ # Parse limit clause+ match = re.search(r"limit\s+(\d+)", query, flags=re.DOTALL | re.IGNORECASE)+ if match:+ limit = match.group(1)++ # Parse similar clauses+ for x, match in enumerate(re.finditer(r"similar\((.+?)\)", query, flags=re.DOTALL | re.IGNORECASE)):+ # Replace similar clause with placeholder+ query = query.replace(match.group(0), f"{Query.SIMILAR}{x}")++ # Parse similar clause parameters+ params = [param.strip().replace("'", "").replace('"', "") for param in match.group(1).split(",")]+ nodes.append(params[0])+ similar.append(params[1:])++ # Return parsed query+ return {+ "query": query,+ "where": where,+ "limit": limit,+ "nodes": nodes,+ "similar": similar,+ }++ def build(self, parse):+ """+ Constructs a full query from a parsed query. This method supports substituting placeholders with search results.++ Args:+ parse: parsed query++ Returns:+ graph query+ """++ # Get query. Initialize attributes and uids.+ query, attributes, uids = parse["query"], {}, {}++ # Replace similar clause with id query+ if "results" in parse:+ for x, result in enumerate(parse["results"]):+ # Get query node+ node = parse["nodes"][x]++ # Add similar match attribute+ attribute = f"match_{x}"+ clause = f"{node}.{attribute} > 0"++ # Replace placeholder with earch results+ query = query.replace(f"{Query.SIMILAR}{x}", f"{clause}")++ # Add uids and scores+ for uid, score in result:+ if uid not in uids:+ uids[uid] = score++ # Add results by attribute matched+ attributes[attribute] = result++ # Return query, results by attribute matched and ids filter+ return query, attributes, uids.items()++ def filter(self, graph, attributes, uids):+ """+ Filters the input graph by uids. This method also adds similar match attributes.++ Args:+ graph: graph instance+ attributes: results by attribute matched+ uids: single list with all matching ids++ Returns:+ filtered graph+ """++ # Filter the graph+ graph = graph.filter(uids)++ # Add similar match attributes+ for attribute, result in attributes.items():+ for uid, score in result:+ graph.addattribute(uid, attribute, score)++ return graphdiff --git a/test/python/testgraph.py b/test/python/testgraph.pyindex 6438f3a6..1f40f5c2 100644--- a/test/python/testgraph.py+++ b/test/python/testgraph.py@@ -319,8 +319,9 @@ class TestGraph(unittest.TestCase):self.assertRaises(NotImplementedError, graph.centrality)self.assertRaises(NotImplementedError, graph.pagerank)self.assertRaises(NotImplementedError, graph.showpath, None, None)- self.assertRaises(NotImplementedError, graph.search, None)self.assertRaises(NotImplementedError, graph.isquery, None)+ self.assertRaises(NotImplementedError, graph.parse, None)+ self.assertRaises(NotImplementedError, graph.search, None)self.assertRaises(NotImplementedError, graph.communities, None)self.assertRaises(NotImplementedError, graph.load, None)self.assertRaises(NotImplementedError, graph.save, None)@@ -461,6 +462,19 @@ class TestGraph(unittest.TestCase):)self.assertEqual(g.count(), 3)+ # Run similar search+ results = self.embeddings.search(+ """+ MATCH P=(A)-[]->()+ WHERE SIMILAR(A, "feel good story")+ RETURN A+ ORDER BY A.score DESC+ LIMIT 1+ """,+ graph=True,+ )+ self.assertEqual(list(results.scan())[0], 4)+def testSearchBatch(self):"""Test batch searchdiff --git a/test/python/testoptional.py b/test/python/testoptional.pyindex c5770209..11f637d8 100644--- a/test/python/testoptional.py+++ b/test/python/testoptional.py@@ -30,8 +30,8 @@ class TestOptional(unittest.TestCase):"duckdb","fastapi","gliner",- "grand-cypher",- "grand-graph",+ "grandcypher",+ "grand","hnswlib","imagehash","libcloud.storage.providers",@@ -158,7 +158,7 @@ class TestOptional(unittest.TestCase):Test missing graph dependencies"""- from txtai.graph import GraphFactory+ from txtai.graph import GraphFactory, Querywith self.assertRaises(ImportError):GraphFactory.create({"backend": "networkx"})@@ -166,6 +166,9 @@ class TestOptional(unittest.TestCase):with self.assertRaises(ImportError):GraphFactory.create({"backend": "rdbms"})+ with self.assertRaises(ImportError):+ Query()+def testModel(self):"""Test missing model dependencies