Haystack docs home page

Module base

Module text_to_sparql

Text2SparqlRetriever Objects

class Text2SparqlRetriever(BaseGraphRetriever)

Graph retriever that uses a pre-trained Bart model to translate natural language questions given in text form to queries in SPARQL format. The generated SPARQL query is executed on a knowledge graph.


| __init__(knowledge_graph, model_name_or_path, top_k: int = 1)

Init the Retriever by providing a knowledge graph and a pre-trained BART model


  • knowledge_graph: An instance of BaseKnowledgeGraph on which to execute SPARQL queries.
  • model_name_or_path: Name of or path to a pre-trained BartForConditionalGeneration model.
  • top_k: How many SPARQL queries to generate per text query.


| retrieve(query: str, top_k: Optional[int] = None)

Translate a text query to SPARQL and execute it on the knowledge graph to retrieve a list of answers


  • query: Text query that shall be translated to SPARQL and then executed on the knowledge graph
  • top_k: How many SPARQL queries to generate per text query.


| format_result(result)

Generate formatted dictionary output with text answer and additional info


  • result: The result of a SPARQL query as retrieved from the knowledge graph