Skip to main content

GraphRAG Extract

ai_extract turns unstructured text into structured, relational data - directly in SQL. You describe what you want in plain language, point it at a query that returns text, and Timbr uses an LLM to extract entities, relationships, facts, metrics, sentiment and classifications into a table you can query, join with your structured data, and map into your knowledge graph.

ai_extract is the engine behind the GraphRAG Extract page in the Timbr UI. The UI adds file upload (PDF, text and Markdown documents) on top of the same engine. the SQL function runs it over any text you can select with a query - ontology concepts or raw datasource tables.

It is deployed as part of the graph algorithms service and is exposed as a table function in the gtimbr schema.


What you get​

No external pipelines, no prompt engineering, no post-processing scripts. A single SQL statement gives you:

  • Extraction - write a business-level instruction ("extract companies, their investors and acquisition events"). Timbr analyzes your instruction together with a sample of your data, derives the output columns from your goal, and applies the same extraction logic consistently to every row.
  • Flattening - results are always flat, relational rows: no nested JSON, no arrays. Relationships are encoded as columns on the same row (subject, related entity, relation type), so the output is immediately joinable and ready to be modeled as concepts and relationships.
  • Value harmonization - category and label columns (entity roles, relation types, sentiment labels, categories) are kept consistent across the whole run. Variants of the same value in different spelling, casing or abbreviation (FinTech, fintech, Financial Technology) converge to one canonical value, so you can group, filter and join on them without cleanup or lookup tables.
  • Normalization - numbers, percentages and dates are normalized (50k → 50000, 4.5% → 0.045, dates in ISO YYYY-MM-DD). Text keeps its original language.
  • Traceability - every extracted row carries the ID of the source row it came from, so results can always be traced back and joined to the original record.
  • Grounded output - values are extracted from the text, not invented. When a requested field is not present in the text, the row is still returned with NULL for that field, instead of being dropped or guessed.

Syntax​

SELECT * FROM gtimbr.ai_extract(
({timbr_sql_query}),
`instructions` = '{what_to_extract}',
`schema` = '{output_schema}',
{parameter} = '{value}', ...
)
note

The inner query must be wrapped in its own parentheses, separate from the function call parentheses. This is how the parser distinguishes the query from the named parameters.

Input query structure​

  • First column - a unique identifier (row ID, entity ID, document ID, file name, etc.). This ID is attached to every extracted row, under the same column name, and is the key for mapping results back to the ontology.
  • Second column onward - one or more text columns. All of them are passed to the LLM together as the context for extraction.
  • The inner query can target Timbr ontology concepts (for example dtimbr.<concept>) or datasource tables directly.

Parameters​

ParameterDefaultDescription
instructionsrequiredPlain-language description of what to extract.
schemarequiredSchema the output table is written to. The executing user must have write access to it.
tablegeneratedName of the output table. If the table already exists, the extracted rows are appended to it, keeping its existing columns.
async'false''true' runs the extraction in the background and returns immediately. 'false' waits for the extraction to finish and returns the extracted rows. See Sync vs. async.
drop_table_after_run'true'Sync runs only. Whether the output table is dropped after the results are returned. Set to 'false' to keep the table after a sync run. Async runs always keep the table.
llm_iduser's active LLMThe LLM to use for the extraction. When omitted, the user's active LLM is used, or the first LLM the user has access to.
parallel'2'Number of concurrent LLM calls. Increase for large datasets, within the rate limits of your LLM provider.
sample'10'Number of input rows analyzed up front to tailor the extraction to your instructions and data.
batch_size'1000'Number of extracted rows written to the output table per batch.
enable_harmonization'true'Whether to harmonize category and label values across the run. See Value harmonization.
harmonize_max_unique'5000'Maximum number of distinct values tracked per harmonized column. Increase (for example up to '50000') when a harmonized column legitimately has many distinct values.
retry_extraction'1'Auto-correct step: when an extraction attempt fails or comes back empty on text that clearly has content, the input is re-evaluated. '0' disables the retry.

Sync vs. async​

async = 'false' (default)async = 'true'
Query returnsAfter the extraction completesImmediately
ResultThe extracted rowsA single row with schema, table and job_id
Output tableDropped after the query, unless drop_table_after_run = 'false'Kept in the target schema
Best forExploration, testing instructions on a few rowsLarge datasets, production workloads

Async runs are tracked as jobs with job_type = 'ai_extract'. Use the returned job_id to follow progress - while running, the job status reports how many rows have been inserted so far:

-- Running extractions
SELECT job_id, status, start_time, last_update
FROM timbr.sys_jobs_running
WHERE job_type = 'ai_extract';

-- Completed extractions
SELECT job_id, target_name, status, number_of_rows, duration, status_log
FROM timbr.sys_jobs_history
WHERE job_type = 'ai_extract'
ORDER BY start_time DESC;

A job that finishes with some rows that could not be written reports Completed with warnings in status_log. See Cache/Jobs tables.


Output​

Every extracted row contains the ID column of your input query plus the columns derived from your instructions. When your instructions don't name the fields explicitly, Timbr uses a standard, flat structure:

ColumnDescription
record_typeKind of record: entity, fact, classification or sentiment.
subject_roleRole of the extracted subject (for example company_name, product_aspect).
subject_valueThe extracted subject itself.
related_role, related_value, relation_typeThe related entity and the type of relationship - only when relationships are requested.
relation_timeWhen the relationship happened - only for time-bound relationships.
metric_name, metric_value, metric_value_typeA named numeric fact and its normalized value - only when metrics are requested.
sentiment_label, sentiment_targetAspect-based sentiment - only when sentiment is requested.
subject_*, related_*, metric_*Additional attributes you ask for (date, currency, location, status...), prefixed by the element they describe.

A single source row can produce many extracted rows - one per entity, fact, relationship or sentiment found in its text. If you describe the fields you want ("extract company_name, founding_year and headquarters_city"), the output follows your structure instead.

The output schema adapts during the run: when a later batch finds a field that earlier batches didn't, the column is added to the table automatically.

Value harmonization​

With enable_harmonization = 'true', Timbr identifies which output columns hold categories or labels, based on your instructions, and keeps their values consistent throughout the run. As batches are extracted, new values are matched against the values already seen, so the same concept always ends up with the same label - across thousands of rows and across documents.

harmonize_max_unique limits how many distinct values are tracked per column. Columns that are genuinely categorical stay well below the default of 5000. if a column you want harmonized has more distinct values than that (for example product or organization names across a large corpus), increase it, for example to '50000'.


Examples​

Entity and relationship extraction​

SELECT * FROM gtimbr.ai_extract(
(
SELECT 'p:1' AS product_id,
'Acme Analytics is a BI platform founded in 2015. Integrates with Salesforce and Snowflake, serving 4,000+ enterprise customers. Acquired by DataCorp Inc. in 2022.' AS description
UNION ALL
SELECT 'p:2',
'NovaPay offers embedded payment infrastructure for SaaS platforms. Processes $2B+ in annual volume. Backed by Sequoia Capital.'
),
`instructions` = 'Extract entities and relationships: company names, integrations, acquisition events, investor relationships. Normalize numerics.',
`schema` = 'graph_rag_output'
)

Sample output:

product_idrecord_typesubject_rolesubject_valuerelated_rolerelated_valuerelation_type
p:1entitycompany_nameAcme AnalyticsNULLNULLNULL
p:1factcompany_nameAcme AnalyticsintegrationSalesforceintegrates_with
p:1factcompany_nameAcme Analyticsacquired_byDataCorp Inc.acquired
p:2entitycompany_nameNovaPayNULLNULLNULL
p:2factcompany_nameNovaPayinvestorSequoia Capitalbacked_by

Aspect-based sentiment​

SELECT * FROM gtimbr.ai_extract(
(
SELECT 'ticket:101' AS ticket_id,
'Onboarding was smooth and support was very responsive. However, the reporting dashboard is slow and exports keep timing out.' AS feedback
UNION ALL
SELECT 'ticket:102',
'Pricing is fair. The API docs are excellent. Wish the mobile app had more features - it feels limited vs the web version.'
),
`instructions` = 'Extract aspect-based sentiment. For each aspect: name, sentiment_label (positive/negative/neutral), sentiment_target.',
`schema` = 'graph_rag_output'
)

Sample output:

ticket_idrecord_typesubject_rolesubject_valuesentiment_labelsentiment_target
ticket:101sentimentproduct_aspectonboardingpositiveonboarding experience
ticket:101sentimentproduct_aspectdashboardnegativereporting dashboard speed
ticket:101sentimentproduct_aspectexportnegativeexport feature reliability
ticket:102sentimentproduct_aspectpricingpositivevalue for money
ticket:102sentimentproduct_aspectmobile_appnegativemobile feature completeness

Classification over an ontology concept, in the background​

Classify all support cases into a persistent table, with a specific LLM and a wider harmonization limit:

SELECT * FROM gtimbr.ai_extract(
(SELECT case_id, subject, description FROM dtimbr.support_case),
`instructions` = 'Classify each case: category (bug/how-to/billing/feature-request), priority (critical/high/medium/low), affected_plan, one-line summary.',
`schema` = 'graph_rag_output',
`table` = 'support_case_classification',
`llm_id` = 'my_llm',
`parallel` = '8',
`harmonize_max_unique` = '50000',
`async` = 'true'
)

The query returns immediately with the schema, table and job_id of the run. Running it again with the same table appends the new results to the existing table.

Keep the table of a sync run​

SELECT * FROM gtimbr.ai_extract(
(SELECT case_id, description FROM dtimbr.support_case LIMIT 5),
`instructions` = 'Classify each case by category and priority.',
`schema` = 'graph_rag_output',
`table` = 'case_classification_test',
`drop_table_after_run` = 'false'
)

Mapping results back to the ontology​

The first column of your input query is preserved in every extracted row. Once the output table exists, map it into the knowledge graph as a new concept and use that ID column as the relationship to the source concept. You can then:

  • Join extracted entities and facts with the structured attributes of the same entity.
  • Traverse relationships between extracted and structured data in a single query.
  • Expose the enriched ontology to Data Agents, so a single agent answers questions that span both structured and unstructured data.

The GraphRAG Extract page can do this mapping for you with Integrate.


Permissions​

The executing user must have write access to the schema specified in schema. Without it, the function fails when creating the output table. The user must also have access to the LLM used for the extraction.


Tips for writing good instructions​

  • Be specific about what matters. Focused instructions produce cleaner, more useful output. Avoid open-ended instructions like "extract everything".
  • Name the fields you want. If you know the output structure, describe it: "extract company_name, founding_year and headquarters_city as separate fields".
  • List allowed values for categories. "category (bug/how-to/billing/feature-request)" gives harmonization a clear target.
  • Use business terminology. Write instructions the way a business analyst would describe the task - no technical or prompt language needed.
  • Validate on a small sample first. Run sync with LIMIT 5 on the inner query to check your instructions before running async on the full dataset.
  • Specify normalization expectations. If you need a specific unit, currency or date format, say so in the instructions.