Zero Labs
Industry News / AI

Building SEC EDGAR Financial Analytics With CocoIndex and Apache Doris

Source · Towards AI By Cocoindex

From the publisher’s feed, collected in the ZeroLabs newsroom.

SEC filings are the backbone of financial transparency. Every public company in the United States files 10-Ks, 10-Qs, proxy statements, and exhibits with the SEC — thousands of documents each quarter across text, structured data, and PDF formats.Searching across all of these effectively requires more than keyword matching. You need semantic understanding, structured metadata filtering, and the ability to combine multiple document formats into a single searchable index.In this post, we walk through the SEC EDGAR Financial Analytics example: a CocoIndex pipeline that ingests three source types (TXT filings, JSON company facts, PDF exhibits), scrubs PII, extracts topic tags, generates embeddings, and exports everything into Apache Doris for hybrid search that combines vector similarity with full-text matching using Reciprocal Rank Fusion (RRF). The project is fully open sourced on GitHub.Why CocoIndex?CocoIndex is a Rust-based, open-source data transformation framework for AI workloads, combining high performance with flexibility. It supports incremental processing, data lineage, and customizable logic, allowing teams to build efficient and intelligent data pipelines. CocoIndex makes transformation pipelines modular, transparent, and easy to maintain.Why Apache Doris?Apache Doris is an open-source, Apache-licensed real-time MPP data warehouse built for lightning-fast analytics. It supports high-concurrency workloads with real-time data ingestion and querying, handles both structured and semi-structured (VARIANT) data, includes full-text inverted indexes, and features native vector storage and approximate nearest neighbor (ANN) search.Together, CocoIndex and Apache Doris form a powerful agentic data infrastructure stack. CocoIndex transforms and indexes unstructured data through modular, lineage-tracked pipelines with built-in incremental processing, while Apache Doris delivers real-time analytics at scale with sub-second ingestion latency, sub-100ms query response, and 10k QPS concurrency — capabilities purpose-built for AI agents that need to make fast, data-driven decisions. The combination bridges the gap from raw, unstructured data to ultra-performant real-time search and analytics, while CocoIndex’s data lineage and transparency ensure the auditability and compliance that regulated industries demand.Architecture OverviewThe pipeline follows a multi-source, unified-collector pattern. Three different file formats feed into a single collector. Each source extracts its own metadata and performs PII scrubbing, splitting, embedding, and topic extraction. The output lands in a single Doris table with both vector and full-text indexes.Define the CocoIndex FlowThe entry point is a single @cocoindex.flow_def that wires up three sources, a shared collector, and a Doris export target.Defining the sourcesEach source uses LocalFile with pattern filtering and a refresh interval, so the pipeline keeps the index fresh as new filings arrive.@cocoindex.flow_def(name="SECFilingAnalytics")def sec_filing_flow(flow_builder, data_scope) -> None: # TXT filings (10-K risk factors, plain text) data_scope["txt_filings"] = flow_builder.add_source( cocoindex.sources.LocalFile(path="data/filings", included_patterns=["*.txt"]), refresh_interval=timedelta(hours=1), ) # JSON company facts (SEC XBRL API format) data_scope["json_facts"] = flow_builder.add_source( cocoindex.sources.LocalFile(path="data/company_facts", included_patterns=["*.json"]), refresh_interval=timedelta(hours=1), ) # PDF exhibits (binary mode for docling conversion) data_scope["pdf_exhibits"] = flow_builder.add_source( cocoindex.sources.LocalFile(path="data/exhibits_pdf", included_patterns=["*.pdf"], binary=True), refresh_interval=timedelta(hours=1), )The Unified CollectorRather than exporting each source separately, a single collector merges all three into one table. Each source processes its documents independently, but they all feed into the same chunk_collector with the same schema. This is the key design pattern: different source formats, one search index.Processing the Text Filingsextract_filing_metadata parses the structured filename convention {CIK}_{date}_{form}.txt to pull out the company identifier (CIK), filing date, and form type (10-K, 10-Q, etc.) — metadata needed for filtering and aggregation at query time.CocoIndex supports parsing and extraction by LLM natively in many of its examples. In this case, we intentionally used a deterministic parser (generated by an LLM and validated), with no LLM involved at runtime. When you know the file format upfront, a regex or string parser is faster, cheaper, and more reliable than calling an LLM on every document.The process_and_collect function is where the real work happens, and the order of operations matters:Scrub PII before chunking. PII (Social Security numbers, phone numbers, email addresses) can appear in SEC filings inadvertently — there are even SEC rules about this (Reg S-T Rule 83). Scrubbing happens on the full document before chunking, so a phone number or SSN split across a chunk boundary can’t slip through into the search index.Split into chunks. Chunk size is a tradeoff: too large and you lose search resolution, too small and each chunk lacks enough context to be meaningful. We use 1,000 characters with 200-character overlap as a practical middle ground. SplitRecursively respects document structure — it tries to break at markdown headings, then paragraphs, then sentences, before falling back to character boundaries — preserving semantic coherence within each chunk.Per-chunk: embed, extract topics, and collect. For each chunk we generate an embedding vector (for semantic search) and extract topic tags (for structured filtering), then assemble a row combining the chunk’s text, embedding, and topics with the document-level metadata inherited from the parent document.with doc["chunks"].row() as chunk: chunk["embedding"] = text_to_embedding(chunk["text"]) chunk["topics"] = chunk["text"].transform(extract_topics) collector.collect( chunk_id=cocoindex.GeneratedField.UUID, source_type=metadata["source_type"], doc_filename=doc["filename"], location=chunk["location"], cik=metadata["cik"], filing_date=metadata["filing_date"], form_type=metadata["form_type"], fiscal_year=metadata["fiscal_year"], text=chunk["text"], embedding=chunk["embedding"], topics=chunk["topics"], )Topics are extracted as string arrays, which enables array filtering in Doris. The extractor produces tags like [“RISK:CYBER”, “TOPIC:AI”] that can later be filtered with json_contains(topics, ‘“RISK:CYBER”’).Processing JSON Facts and PDF ExhibitsJSON company facts and PDF exhibits follow the same pattern: extract metadata, convert to searchable text, then feed into the shared process_and_collect pipeline. For JSON facts, extract_json_metadata parses the CIK and entity name from the SEC XBRL format, while parse_company_facts converts structured financial metrics (revenue, net income, etc.) into natural language text so they’re discoverable via semantic search. For PDF exhibits, pdf_to_markdown uses docling to convert binary PDF bytes into markdown text before the same processing runs.Exporting to DorisThe export step creates the Doris table with two indexes on the same table: an HNSW vector index on the embedding field for semantic similarity search, and an inverted index on the text field for keyword matching with MATCH_ANY. This dual-index setup is what makes hybrid search possible without maintaining separate stores.chunk_collector.export( "filing_chunks", coco_doris.DorisTarget( fe_host=DORIS_FE_HOST, query_port=DORIS_QUERY_PORT, database=DORIS_DATABASE, table=TABLE_CHUNKS, ), primary_key_fields=["chunk_id"], vector_indexes=[ cocoindex.VectorIndexDef( field_name="embedding", metric=cocoindex.VectorSimilarityMetric.L2_DISTANCE, ) ], fts_indexes=[ cocoindex.FtsIndexDef(field_name="text", parameters={"parser": "unicode"}) ],)Hybrid Search With RRFThe search function combines semantic and lexical ranking using Reciprocal Rank Fusion. The RRF formula 1/(k + rank) with k=60 is a standard approach for combining rankings from different signals without needing to normalize scores. A chunk that ranks #1 in both semantic and lexical search gets 1/61 + 1/61 = 0.0328. A chunk that’s #1 semantically but #100 lexically gets 1/61 + 1/160 = 0.0226. The formula naturally balances both signals.The search also supports optional filters: time_gate_days restricts to filings within the last N days, and source_types filters by document type (“filing”, “facts”, “exhibit”).WITHsemantic AS ( SELECT chunk_id, doc_filename, cik, filing_date, source_type, text, topics, ROW_NUMBER() OVER (ORDER BY l2_distance(embedding, {embedding})) AS rank FROM {table} WHERE {where}),lexical AS ( SELECT chunk_id, ROW_NUMBER() OVER (ORDER BY CASE WHEN text MATCH_ANY '{keywords}' THEN 0 ELSE 1 END) AS rank FROM {table} WHERE {where})SELECT s.*, l.rank AS lex_rank, 1.0/(60 + s.rank) + 1.0/(60 + l.rank) AS scoreFROM semantic s JOIN lexical l USING (chunk_id)ORDER BY score DESC LIMIT {limit}Running the ExampleYou’ll need Python 3.11+ and Docker (for Doris and PostgreSQL). The quick start sets up tables and runs the pipeline:cd examples/sec_edgar_analytics# Install dependenciespip install -e .# Start infrastructure (wait ~90s for Doris to initialize)docker compose up -d# Configure environmentcp .env.example .env# Generate sample datapython -c "from download import create_sample_data; create_sample_data()"# Set up tables and run the pipelinecocoindex setup main.pycocoindex update main.py# Interactive searchpython main.pyThen run cocoindex server -ci main.py and open CocoInsight to see the full data lineage — which source files produced which chunks, how transformations flow through the pipeline, and the complete graph from raw document to indexed embedding.Direct Doris QueriesBecause everything lands in Doris, you can also query the index directly over the MySQL protocol — array filtering on topics, per-company portfolio aggregation, and temporal trend analysis across fiscal years:-- Find all chunks tagged with cybersecurity riskSELECT doc_filename, text, topicsFROM sec_analytics.filing_chunksWHERE json_contains(topics, '"RISK:CYBER"');-- Cybersecurity mentions by fiscal yearSELECT fiscal_year, COUNT(DISTINCT cik) AS num_companies, COUNT(*) AS total_mentionsFROM sec_analytics.filing_chunksWHERE text MATCH_ANY 'cybersecurity risk'GROUP BY fiscal_yearORDER BY fiscal_year DESC;What’s NextThe techniques in this example — multi-source ingestion, array field filtering, hybrid search, PII scrubbing, and temporal scoring — generalize well beyond financial documents. The same patterns apply to healthcare records, legal documents, or any domain where you need to search across heterogeneous document formats with structured metadata filtering. CocoIndex handles the messy transformation work and keeps everything incrementally fresh, while Apache Doris delivers the real-time, sub-second search and analytics that production AI agents depend on.If this example was helpful, the easiest way to support CocoIndex is to give the project a star on GitHub. The full source code, including a Jupyter notebook tutorial for interactive exploration, is available in the CocoIndex examples repository.Building SEC EDGAR Financial Analytics With CocoIndex and Apache Doris was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.