<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Omri Eliyahu Levy on Medium]]></title>
        <description><![CDATA[Stories by Omri Eliyahu Levy on Medium]]></description>
        <link>https://medium.com/@omri-levy?source=rss-339c4d4bc6d4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7foAQb1x3lhkUf9IALye_Q.png</url>
            <title>Stories by Omri Eliyahu Levy on Medium</title>
            <link>https://medium.com/@omri-levy?source=rss-339c4d4bc6d4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 10:10:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@omri-levy/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Achieve Structured Output in Claude 3.7: Three Practical Approaches]]></title>
            <link>https://pub.towardsai.net/how-to-achieve-structured-output-in-claude-3-7-three-practical-approaches-429f7b2ca4ec?source=rss-339c4d4bc6d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/429f7b2ca4ec</guid>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[anthropic-claude]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Omri Eliyahu Levy]]></dc:creator>
            <pubDate>Tue, 13 May 2025 16:02:39 GMT</pubDate>
            <atom:updated>2025-05-13T16:02:39.062Z</atom:updated>
            <content:encoded><![CDATA[<h4>Achieve structured output with Claude Sonnet 3.7 with (and without) extended thinking</h4><p><strong>TL;DR</strong> — Full code can be found <a href="https://gist.github.com/omriel1/47e2c9a8afcb4863c8e16fc524c5ec4a">here</a></p><p>At<a href="https://baz.co/"> Baz</a>, we’re building an AI code review agent that combines static analysis with LLMs to reason deeply about code. Along the way, structured output has become essential, especially when chaining model outputs or integrating into larger systems. As part of that journey, we constantly evaluate and integrate new models to see how they perform in complex, real-world pipelines.</p><p>Anthropic’s recently released <a href="https://www.anthropic.com/claude/sonnet">Claude Sonnet 3.7</a> has attracted a lot of attention for its enhanced reasoning and code understanding. But if you’re building GenAI apps in the wild, there’s a catch: structured output doesn’t work the way you might expect when using its powerful “extended thinking” mode.</p><p><strong>Structured output is critical in production-grade LLM systems</strong> — the ability to get consistent, parseable responses that adhere to a defined schema. Whether you’re routing LLM output to downstream systems or building modular agent workflows, you need more than free-form text — you need structure you can rely on.</p><p>This post walks through what structured output is, why it matters in production, and three practical ways to achieve it with Sonnet 3.7. We include end-to-end examples using <a href="https://github.com/langchain-ai/langchain">Langchain</a> and AWS <a href="https://aws.amazon.com/bedrock/?trk=66201650-d244-48f7-91d2-4f54a5b0ae07&amp;sc_channel=ps&amp;ef_id=Cj0KCQjw_JzABhC2ARIsAPe3ynrG8cv-nNCAuraa-S2KVS2oJoncN-mV9Vr6mj4wmSVikcbASnpW5v4aAnO7EALw_wcB:G:s&amp;s_kwcid=AL!4422!3!717563062224!e!!g!!bedrock!21818514907!169838291238&amp;gbraid=0AAAAADjHtp92skQFjpRNedFObhVw1przR&amp;gclid=Cj0KCQjw_JzABhC2ARIsAPe3ynrG8cv-nNCAuraa-S2KVS2oJoncN-mV9Vr6mj4wmSVikcbASnpW5v4aAnO7EALw_wcB">Bedrock</a> to help others shipping GenAI apps navigate this tradeoff.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8pp99NaWJ81WSXKHpWLMWA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@weird_ographer?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Tamilazhagan</a> on <a href="https://unsplash.com/photos/black-metal-frame-in-grayscale-photography-_QSGGiWbUcA?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><h3>What “structured output” is?</h3><p>Structured output refers to an LLM response that adheres to a predefined schema. Instead of receiving the LLM response as free text, it is returned in a JSON schema that is easy to parse and work with. For production environments, leveraging structured JSON responses is crucial as this is how systems interact today.</p><p><strong>How does structured output work?</strong></p><p>Generally speaking, there are three different ways to achieve structured output:</p><ol><li>Ask the model to adhere to a predefined schema.</li><li>Use constrained generation.</li><li>Utilize function (tool) calling.</li></ol><p>Let’s discuss each.</p><h4>Prompt the model to do so</h4><p>This is the simplest approach but also the least reliable. You simply instruct the model to return its response in a specific format, such as JSON. You can add a few-shot examples, of course, and then try to parse the response directly into JSON.</p><p>The drawback here is that the model might not perfectly follow your instructions, or the schema might be too complex, requiring additional parsing or error handling.</p><h4>Constrained decoding</h4><p>Also sometimes called “JSON mode.” In this approach, there is a restriction on the tokens that the model is allowed to generate at a certain point in time. That is, given the desired output schema, it is translated into a <a href="https://en.wikipedia.org/wiki/Context-free_grammar">context-free grammar</a> that represents the schema [1]. Then, when generating the n’th token, the model will choose only from the tokens it is allowed to produce according to the grammar.</p><p>For example, if the model has already produced:</p><pre>{“key”: “val</pre><p>It will not be allowed to generate the } token as it must close the quotes &quot; on the val(or generate more “letters”) in order to be a valid JSON.</p><p>This approach is great, although some research shows it may harm model performance and quality [2]. Also, Anthropics’ Sonnet 3.7 does not support this option.</p><h4>Function/tool calling</h4><p>In this approach, models are fine-tuned to generate structured outputs that specify which function to call and with what arguments. Function calling is learned through fine-tuning, allowing the model to decide when and how to invoke external functions based on the context of the conversation.</p><p>For example, we can inform the model that it has a web_search function available, which takes a queryas an input, which should be a valid string. So the model is expected to produce a valid function call (tool use) of the following schema:</p><pre>{&quot;function&quot;: &quot;web_search&quot;, &quot;arguments&quot;: {&quot;query&quot;: &quot;when did Claude Sonnet 3.7 come out?&quot; }</pre><p><strong>This is the mode supported by Anthropics’ models!</strong></p><p>Now, if you think about it, if a model knows how to produce high-quality function calls by adhering to their schema, it can actually be utilized to produce any schema. Indeed, this is what Anthropic recommends [4]:</p><p>“<em>Tools do not necessarily need to be client-side functions — you can use tools anytime you want the model to return JSON output that follows a provided schema</em>.“</p><p>By the way, if you’re a Langchain user, when you provide structured output for Anthropic models, it is “translated” behind the scenes into “function calling.”</p><h3>Claude sonnet 3.7</h3><p>Sonnet 3.7 is the latest model by Anthropic which includes enhanced reasoning capabilities. Actually, one can choose to operate with Sonnet 3.7 in one of two modes: <strong>with</strong> or <strong>without</strong> extended thinking. According to Anthropic [5], without thinking it’ll act as an improved version of 3.5 which we know and love, and with thinking enabled it’ll think and reflect (up to a threshold of tokens you can set) and just then will answer. This approach seems to prove itself as it scores very high on the Aider benchmark [6].</p><p><strong>Ok… what’s the catch?</strong></p><p>When extended thinking is on — Sonnet 3.7 does not support some features we were used to, in particular forced tool calling. Or in other words (recall our intro) it does not support structured output.</p><p>Indeed, and citing from the Langchain wrapper to Anthropics’ sourcecode [7]</p><p>“<em>Anthropic structured output relies on forced tool calling, which is not supported when `thinking` is enabled</em>”.</p><p>To be precise, as the Anthropic docs state, besides “forced tool use”, also temperature, top_p, or top_k are not supported.</p><p><strong>What can we do?</strong></p><p>I’ll introduce 3 different ways to achieve structured output with Sonnet 3.7.</p><p>In order to explore different ways I’ll be using Langchain with Anthropic models via AWS bedrock — but it’ll work the same with Anthropic as the provider.</p><p>Lets assume we want the model to be able to create a short story on some provided topic and also determine its genre.</p><pre>from typing import Any<br>from dotenv import load_dotenv<br>from langchain_aws import ChatBedrockConverse<br>from langchain_core.prompts import PromptTemplate<br>from langchain_core.runnables import RunnablePassthrough, RunnableParallel<br>from pydantic import BaseModel, Field<br><br>load_dotenv(&#39;.env&#39;)<br><br>class Story(BaseModel):<br>    &quot;&quot;&quot;A short story with its genre&quot;&quot;&quot;<br>    content: str = Field(description=&#39;A very short story&#39;)<br>    genre: str = Field(description=&#39;The genre of the story&#39;)</pre><h4><strong>“No thinking” mode</strong></h4><p>In this approach, we will <strong>not</strong> use the extended thinking mode of Sonnet 3.7. Without thinking enabled we can get reliable structured outputs through tool calling.</p><pre>def no_thinking_mode() -&gt; Story:<br>    &quot;&quot;&quot;<br>    Example of structured output without extended thinking mode.<br>    This approach disables Claude&#39;s extended thinking capabilities but allows<br>    for direct structured output via forced tool calling.<br>    &quot;&quot;&quot;<br>    prompt = PromptTemplate.from_template(&#39;Create a very short story about: {topic} and determine its genre&#39;)<br><br>    llm = ChatBedrockConverse(<br>        model_id=&#39;us.anthropic.claude-3-7-sonnet-20250219-v1:0&#39;,<br>        region_name=&#39;us-east-2&#39;,<br>        additional_model_request_fields={&#39;thinking&#39;: {&#39;type&#39;: &#39;disabled&#39;}},<br>    )<br>    structured_llm = llm.with_structured_output(Story)<br>    chain = prompt | structured_llm<br><br>    res = chain.invoke({&#39;topic&#39;: &#39;Harry Potter&#39;})<br>    assert isinstance(res, Story)<br>    return resp</pre><p>Remember, Langchain is doing here the “work” for us and “translate” this into a function call with the desired schema.</p><h4><strong>“Hopefully structured” mode</strong></h4><p>In this approach, we’ll use thinking mode and “ask nicely” for structured output.</p><p>This approach leverages the enhanced reasoning but relies on careful prompting to get structured results. Then, try to parse it into the required schema.</p><p>In the following example, Langchain will do that for us, but will raise OutputParserExceptionif it fails to do so.</p><pre>def hopefully_structured_mode() -&gt; Story:<br>    &quot;&quot;&quot;<br>    Example of attempting structured output with extended thinking enabled.<br>    It&#39;ll not use forced tool calling and will try to parse the response into the provided schema.<br>    Will raise `OutputParserException` if it fails.<br>    &quot;&quot;&quot;<br>    prompt = PromptTemplate.from_template(<br>        &quot;&quot;&quot;Create a very short story about: {topic} and determine its genre.<br>        IMPORTANT: Your response must be formatted as valid JSON with two fields:<br>        1. content: That is, the story content<br>        2. genre: The genre of the story<br>        &quot;&quot;&quot;<br>    )<br>    llm = ChatBedrockConverse(<br>        model_id=&#39;us.anthropic.claude-3-7-sonnet-20250219-v1:0&#39;,<br>        region_name=&#39;us-east-2&#39;,<br>        additional_model_request_fields={&#39;thinking&#39;: {&#39;type&#39;: &#39;enabled&#39;, &#39;budget_tokens&#39;: 2000}},<br>    )<br>    structured_llm = llm.with_structured_output(Story)  # will try to parse the result according to the provided schema<br>    chain = prompt | structured_llm<br><br>    res = chain.invoke({&#39;topic&#39;: &#39;Harry Potter&#39;})<br>    assert isinstance(res, Story)<br>    return res</pre><h4><strong>“Reason and Structure” mode</strong></h4><p>In this approach we let Sonnet 3.7 do what it is good at, reasoning, and then use another LLM (say <a href="https://www.anthropic.com/claude/haiku">Haiku</a>) to structure its output. This two-step process gives you the best of both worlds but at the cost of additional complexity and latency.</p><pre>def reason_and_structure_mode(inputs: dict[str, Any] = None) -&gt; Story:<br>    &quot;&quot;&quot;<br>    Example of a two-stage approach: reasoning with Sonnet-3.7 followed by structuring with Haiku.<br>    This approach leverages Sonnet&#39;s extended thinking for content generation, then<br>    uses Haiku to transform the output into a structured format.<br>    &quot;&quot;&quot;<br><br>    reasoning_prompt = PromptTemplate.from_template(&#39;Create a very short story about: {topic}&#39;)<br>    reasoning_llm = ChatBedrockConverse(<br>        model_id=&#39;us.anthropic.claude-3-7-sonnet-20250219-v1:0&#39;,<br>        region_name=&#39;us-east-2&#39;,<br>        additional_model_request_fields={&#39;thinking&#39;: {&#39;type&#39;: &#39;enabled&#39;, &#39;budget_tokens&#39;: 2000}},<br>    )<br>    reasoning_chain = reasoning_prompt | reasoning_llm<br><br>    structuring_prompt = PromptTemplate.from_template(<br>        &#39;Structure the provided story into the requested schema and assign &quot;genre&quot; to be {genre}. Story: {reasoning_output}&#39;<br>    )<br>    structuring_llm = ChatBedrockConverse(<br>        model_id=&#39;us.anthropic.claude-3-5-haiku-20241022-v1:0&#39;,<br>        region_name=&#39;us-east-2&#39;,<br>    )<br>    structuring_llm = structuring_llm.with_structured_output(Story)<br>    structuring_chain = structuring_prompt | structuring_llm<br><br>    # Sometimes, we&#39;ll want to pass some of the inputs params directly to the &quot;structuring model&quot;, not only the output of the reasoning model.<br>    # In order to support that, we&#39;ll create a &quot;dummy&quot; function, that just gets the inputs and returns them.<br>    # Then, we can run both the reasoning chain and the dummy function in parallel, and feed the structuring llm both:<br>    #<br>    #               /-&gt; reasoning_chain -&gt; reasoning_output \<br>    # input_params                                            -&gt;  merge_inputs -&gt; structuring_llm<br>    #               \-&gt; dummy_function  -&gt; original_params  /<br>    reason_then_structure_chain = (<br>        RunnableParallel(<br>            reasoning_output=reasoning_chain,<br>            original_inputs=RunnablePassthrough(),<br>        )<br>        | RunnableLambda(lambda x: prepare_structuring_inputs(x[&#39;original_inputs&#39;], x[&#39;reasoning_output&#39;]))<br>        | structuring_chain<br>    )<br><br>    inputs = {&#39;topic&#39;: &#39;Harry Potter&#39;, &#39;genre&#39;: &#39;fantasy&#39;}<br>    res = reason_then_structure_chain.invoke(inputs)<br>    assert isinstance(res, Story)<br>    return res<br><br><br>def prepare_structuring_inputs(original_inputs: dict[str, Any], reasoning_output: str) -&gt; dict[str, Any]:<br>    &quot;&quot;&quot;<br>    Prepares inputs for the structuring model by combining original inputs with reasoning output.<br>    &quot;&quot;&quot;<br>    return {<br>        **original_inputs,  # Pass original inputs as-is<br>        &#39;reasoning_output&#39;: reasoning_output,  # Add reasoning chain output<br>    }<br></pre><p>Full code can be found <a href="https://gist.github.com/omriel1/47e2c9a8afcb4863c8e16fc524c5ec4a">here</a>.</p><p>In summary, while Sonnet 3.7 offers strong reasoning capabilities, achieving reliable structured output in production can be tricky, especially with extended thinking mode. By using approaches like no thinking mode, careful prompting, or combining reasoning with a separate structuring model, you can effectively work around these limitations and integrate structured outputs into your GenAI applications. These methods provide a practical way to ensure seamless integration in real-world pipelines.</p><p><strong>References</strong></p><p>[1]<strong> </strong><a href="https://openai.com/index/introducing-structured-outputs-in-the-api/">https://openai.com/index/introducing-structured-outputs-in-the-api/</a><br>[2] Let Me Speak Freely? A Study on the Impact of Format Restrictions on Performance of Large Language Models: <a href="https://arxiv.org/abs/2408.02442">https://arxiv.org/abs/2408.02442</a><br>[3] <a href="https://huggingface.co/learn/agents-course/bonus-unit1/what-is-function-calling">https://huggingface.co/learn/agents-course/bonus-unit1/what-is-function-calling</a><br>[4] <a href="https://docs.anthropic.com/en/docs/build-with-claude/tool-use/overview#json-output">https://docs.anthropic.com/en/docs/build-with-claude/tool-use/overview#json-output</a><br>[5] <a href="https://www.anthropic.com/news/claude-3-7-sonnet">https://www.anthropic.com/news/claude-3-7-sonnet</a><br>[6] <a href="https://aider.chat/docs/leaderboards/">https://aider.chat/docs/leaderboards/</a><br>[7]<a href="https://github.com/langchain-ai/langchain/blob/47ded80b64fa8bd5d3d2f8cab0fe17fd66689019/libs/partners/anthropic/langchain_anthropic/chat_models.py#L1187">https://github.com/langchain-ai/langchain/blob/47ded80b64fa8bd5d3d2f8cab0fe17fd6668 9019/libs/partners/anthropic/langchain_anthropic/chat_models.py#L1187</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=429f7b2ca4ec" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/how-to-achieve-structured-output-in-claude-3-7-three-practical-approaches-429f7b2ca4ec">How to Achieve Structured Output in Claude 3.7: Three Practical Approaches</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LangChain’s Parent Document Retriever — Revisited]]></title>
            <link>https://medium.com/data-science/langchains-parent-document-retriever-revisited-1fca8791f5a0?source=rss-339c4d4bc6d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fca8791f5a0</guid>
            <category><![CDATA[milvus]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[vector-database]]></category>
            <dc:creator><![CDATA[Omri Eliyahu Levy]]></dc:creator>
            <pubDate>Mon, 22 Jul 2024 06:27:20 GMT</pubDate>
            <atom:updated>2024-11-21T20:40:59.594Z</atom:updated>
            <content:encoded><![CDATA[<h3>LangChain’s Parent Document Retriever — Revisited</h3><h4>Enhance retrieval with context using your vector database only</h4><p><strong>TL;DR </strong>— We achieve the same functionality as LangChains’ Parent Document Retriever (<a href="https://python.langchain.com/v0.1/docs/modules/data_connection/retrievers/parent_document_retriever/">link</a>) by utilizing metadata queries. You can explore the code <a href="https://gist.github.com/omriel1/7243ce233eb2986ed2749de6ae79ecb7">here</a>.</p><h3>Introduction to RAG</h3><p>Retrieval-augmented generation (RAG) is currently one of the hottest topics in the world of LLM and AI applications.</p><p>In short, RAG is a technique for grounding a generative models’ response on chosen knowledge sources. It comprises two phases: retrieval and generation.</p><ol><li>In the retrieval phase, given a user’s query, we retrieve pieces of relevant information from a predefined knowledge source.</li><li>Then, we insert the retrieved information into the prompt that is sent to an LLM, which (ideally) generates an answer to the user’s question based on the provided context.</li></ol><p>A commonly used approach to achieve efficient and accurate retrieval is through the usage of embeddings. In this approach, we preprocess users’ data (let’s assume plain text for simplicity) by splitting the documents into chunks (such as pages, paragraphs, or sentences). We then use an embedding model to create a meaningful, numerical representation of these chunks, and store them in a vector database. Now, when a query comes in, we embed it as well and perform a similarity search using the vector database to retrieve the relevant information</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qv7FtzI8RjYoR4KZTOkPBw.png" /><figcaption>Image by the author</figcaption></figure><p>If you are completely new to this concept, I’d recommend <a href="https://www.deeplearning.ai/">deeplearning.ai</a> great course, <a href="https://www.deeplearning.ai/short-courses/langchain-chat-with-your-data/">LangChain: Chat with Your Data</a>.</p><h3>What is “Parent Document Retrieval”?</h3><p>“Parent Document Retrieval” or “Sentence Window Retrieval” as referred by others, is a common approach to enhance the performance of retrieval methods in RAG by providing the LLM with a broader context to consider.</p><p>In essence, we divide the original documents into relatively small chunks, embed each one, and store them in a vector database. Using such small chunks (a sentence or a couple of sentences) helps the embedding models to better reflect their meaning [1].</p><p>Then, <strong>at retrieval time, we do not return the most similar chunk as found by the vector database only, but also its surrounding context </strong>(chunks)<strong> in the original document</strong>. That way, the LLM will have a broader context, which, in many cases, helps generate better answers.</p><p>LangChain supports this concept via Parent Document Retriever [2]. The Parent Document Retriever allows you to: (1) retrieve the full document a specific chunk originated from, or (2) pre-define a larger “parent” chunk, for each smaller chunk associated with that parent.</p><p>Let’s explore the example from <a href="https://python.langchain.com/v0.1/docs/modules/data_connection/retrievers/parent_document_retriever/">LangChains’ docs</a>:</p><pre># This text splitter is used to create the parent documents<br>parent_splitter = RecursiveCharacterTextSplitter(chunk_size=2000)<br># This text splitter is used to create the child documents<br># It should create documents smaller than the parent<br>child_splitter = RecursiveCharacterTextSplitter(chunk_size=400)<br># The vectorstore to use to index the child chunks<br>vectorstore = Chroma(<br>    collection_name=&quot;split_parents&quot;, embedding_function=OpenAIEmbeddings()<br>)<br># The storage layer for the parent documents<br>store = InMemoryStore()<br>retriever = ParentDocumentRetriever(<br>    vectorstore=vectorstore,<br>    docstore=store,<br>    child_splitter=child_splitter,<br>    parent_splitter=parent_splitter,<br>)<br>retrieved_docs = retriever.invoke(&quot;justice breyer&quot;)</pre><p>In my opinion, there are two disadvantages of the LangChains’ approach:</p><ol><li>The need to manage external storage to benefit from this useful approach, either in memory or another persistent store. Of course, for real use cases, the InMemoryStore used in the various examples will not suffice.</li><li>The “parent” retrieval isn’t dynamic, meaning we cannot change the size of the surrounding window on the fly.</li></ol><p>Indeed, a few questions have been raised regarding this issue [3].</p><p>Here I’ll also mention that Llama-index has its own <a href="https://docs.llamaindex.ai/en/stable/api_reference/node_parsers/sentence_window/">SentenceWindowNodeParser</a> [4], which generally has the same disadvantages.</p><p>In what follows, I’ll present another approach to achieve this useful feature that addresses the two disadvantages mentioned above. In this approach, we’ll be only using the vector store that is already in use.</p><h4>Alternative Implementation</h4><p>To be precise, we’ll be using a vector store that supports the option to perform metadata queries only, without any similarity search involved. Here, I’ll present an implementation for <strong>ChromaDB</strong> and <strong>Milvus</strong>. This concept can be easily adapted to any vector database with such capabilities. I’ll refer to <strong>Pinecone</strong> for example in the end of this tutorial.</p><p><strong>The general concept</strong></p><p>The concept is straightforward:</p><ol><li><strong>Construction:</strong> Alongside each chunk, save in its metadata the <em>document_id</em> it was generated from and also the <em>sequence_number</em> of the chunk.</li><li><strong>Retrieval:</strong> After performing the usual similarity search (assuming for simplicity only the top 1 result), we obtain the <em>document_id</em> and the <em>sequence_number</em> of the chunk from the metadata of the retrieved chunk. Retrieve all chunks with surrounding sequence numbers that have the same <em>document_id</em>.</li></ol><p>For example, assuming you’ve indexed a document named <strong><em>example.pdf </em></strong>in 80 chunks. Then, for some query, you find that the closest vector is the one with the following metadata:</p><pre>{document_id: &quot;example.pdf&quot;, sequence_number: 20}</pre><p>You can easily get all vectors from the same document with sequence numbers from 15 to 25.</p><p>Let’s see the code.</p><p>Here, I’m using:</p><pre>chromadb==0.4.24<br>langchain==0.2.8<br>pymilvus==2.4.4<br>langchain-community==0.2.7<br>langchain-milvus==0.1.2</pre><p>The only interesting thing to notice below is the metadata associated with each chunk, which will allow us to perform the search.</p><pre>from langchain_community.document_loaders import PyPDFLoader<br>from langchain_core.documents import Document<br>from langchain_text_splitters import RecursiveCharacterTextSplitter<br><br>document_id = &quot;example.pdf&quot;<br><br>def preprocess_file(file_path: str) -&gt; list[Document]:<br>    &quot;&quot;&quot;Load pdf file, chunk and build appropriate metadata&quot;&quot;&quot;<br>    loader = PyPDFLoader(file_path=file_path)<br>    pdf_docs = loader.load()<br><br>    text_splitter = RecursiveCharacterTextSplitter(<br>        chunk_size=1000,<br>        chunk_overlap=0,<br>    )<br><br>    docs = text_splitter.split_documents(documents=pdf_docs)<br>    chunks_metadata = [<br>        {&quot;document_id&quot;: file_path, &quot;sequence_number&quot;: i} for i, _ in enumerate(docs)<br>    ]<br>    for chunk, metadata in zip(docs, chunks_metadata):<br>        chunk.metadata = metadata<br><br>    return docs</pre><p>Now, lets implement the actual retrieval in Milvus and Chroma. Note that I’ll use the LangChains’ objects and not the native clients. I do this because I assume developers might want to keep LangChains’ useful abstraction. On the other hand, it will require us to perform some minor hacks to bypass these abstractions in a database-specific way, so you should take that into consideration. Anyway, the concept remains the same.</p><p>Again, let’s assume for simplicity we want only the most similar vector (“top 1”). Next, we’ll extract the associated document_id and its sequence number. This will allow us to retrieve the surrounding window.</p><pre>from langchain_community.vectorstores import Milvus, Chroma<br>from langchain_community.embeddings import DeterministicFakeEmbedding<br><br>embedding = DeterministicFakeEmbedding(size=384) # Just for the demo :)<br><br>def parent_document_retrieval(<br>    query: str, client: Milvus | Chroma, window_size: int = 4<br>):<br>    top_1 = client.similarity_search(query=query, k=1)[0]<br>    doc_id = top_1.metadata[&quot;document_id&quot;]<br>    seq_num = top_1.metadata[&quot;sequence_number&quot;]<br>    ids_window = [seq_num + i for i in range(-window_size, window_size, 1)]<br>    # ...</pre><p>Now, for the window/parent retrieval, we’ll dig under the Langchain abstraction, in a database-specific way.</p><p>For Milvus:</p><pre>  if isinstance(client, Milvus):<br>        expr = f&quot;document_id LIKE &#39;{doc_id}&#39; &amp;&amp; sequence_number in {ids_window}&quot;<br>        res = client.col.query(<br>            expr=expr, output_fields=[&quot;sequence_number&quot;, &quot;text&quot;], limit=len(ids_window)<br>        )  # This is Milvus specific<br>        docs_to_return = [<br>            Document(<br>                page_content=d[&quot;text&quot;],<br>                metadata={<br>                    &quot;sequence_number&quot;: d[&quot;sequence_number&quot;],<br>                    &quot;document_id&quot;: doc_id,<br>                },<br>            )<br>            for d in res<br>        ]<br>    # ...</pre><p>For Chroma:</p><pre>    elif isinstance(client, Chroma):<br>        expr = {<br>            &quot;$and&quot;: [<br>                {&quot;document_id&quot;: {&quot;$eq&quot;: doc_id}},<br>                {&quot;sequence_number&quot;: {&quot;$gte&quot;: ids_window[0]}},<br>                {&quot;sequence_number&quot;: {&quot;$lte&quot;: ids_window[-1]}},<br>            ]<br>        }<br>        res = client.get(where=expr)  # This is Chroma specific<br>        texts, metadatas = res[&quot;documents&quot;], res[&quot;metadatas&quot;]<br>        docs_to_return = [<br>            Document(<br>                page_content=t,<br>                metadata={<br>                    &quot;sequence_number&quot;: m[&quot;sequence_number&quot;],<br>                    &quot;document_id&quot;: doc_id,<br>                },<br>            )<br>            for t, m in zip(texts, metadatas)<br>        ]</pre><p>and don’t forget to sort it by the sequence number:</p><pre>    docs_to_return.sort(key=lambda x: x.metadata[&quot;sequence_number&quot;])<br>    return docs_to_return</pre><p>For your convenience, you can explore the full code <a href="https://gist.github.com/omriel1/7243ce233eb2986ed2749de6ae79ecb7">here</a>.</p><h4>Pinecone (and others)</h4><p>As far as I know, there’s no native way to perform such a metadata query in Pinecone, but you can natively fetch vectors by their ID (<a href="https://docs.pinecone.io/guides/data/fetch-data">https://docs.pinecone.io/guides/data/fetch-data</a>).</p><p>Hence, we can do the following: each chunk will get a unique ID, which is essentially a concatenation of the document_id and the sequence number. Then, given a vector retrieved in the similarity search, you can dynamically create a list of the IDs of the surrounding chunks and achieve the same result.</p><h3>Limitations</h3><p>It’s worth mentioning that vector databases were not designed to perform “regular” database operations and usually not optimized for that, and each database will perform differently. Milvus, for example, will support building indices over scalar fields (“metadata”) which can optimize these kinds of queries.</p><p>Also, note that it requires additional query to the vector database. First we retrieved the most similar vector, and then we performed additional query to get the surrounding chunks in the original document.</p><p>And of course, as seen from the code examples above, the implementation is vector database-specific and is not supported natively by the LangChains’ abstraction.</p><h3>Conclusion</h3><p>In this blog we introduced an implementation to achieve sentence-window retrieval, which is a useful retrieval technique used in many RAG applications. In this implementation we’ve used only the vector database which is already in use anyway, and also support the option to modify dynamically the the size of the surrounding window retrieved.</p><h3>References</h3><p>[1] ARAGOG: Advanced RAG Output Grading, <a href="https://arxiv.org/pdf/2404.01037">https://arxiv.org/pdf/2404.01037</a>, section 4.2.2</p><p>[2] <a href="https://python.langchain.com/v0.1/docs/modules/data_connection/retrievers/parent_document_retriever/">https://python.langchain.com/v0.1/docs/modules/data_connection/retrievers/parent_document_retriever/</a></p><p>[3] Some related issues:</p><p>- <a href="https://github.com/langchain-ai/langchain/issues/14267">https://github.com/langchain-ai/langchain/issues/14267</a><br>- <a href="https://github.com/langchain-ai/langchain/issues/20315">https://github.com/langchain-ai/langchain/issues/20315</a><br>- <a href="https://stackoverflow.com/questions/77385587/persist-parentdocumentretriever-of-langchain">https://stackoverflow.com/questions/77385587/persist-parentdocumentretriever-of-langchain</a></p><p>[4] <a href="https://docs.llamaindex.ai/en/stable/api_reference/node_parsers/sentence_window/">https://docs.llamaindex.ai/en/stable/api_reference/node_parsers/sentence_window/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fca8791f5a0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/langchains-parent-document-retriever-revisited-1fca8791f5a0">LangChain’s Parent Document Retriever — Revisited</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[​​One query plan, three different engines.]]></title>
            <link>https://medium.com/@omri-levy/one-query-plan-three-different-engines-e5dc74aeb52f?source=rss-339c4d4bc6d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5dc74aeb52f</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[query]]></category>
            <category><![CDATA[execution-engine]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Omri Eliyahu Levy]]></dc:creator>
            <pubDate>Wed, 28 Jun 2023 13:04:36 GMT</pubDate>
            <atom:updated>2023-08-02T16:03:51.752Z</atom:updated>
            <content:encoded><![CDATA[<p>A walk-through demo of using Substrait: A cross-language specification for data compute operations.</p><h4><strong>TL;DR</strong></h4><p>First, I will present the Substrait project. Then, I will guide you through a hands-on demo of creating one query plan using Substrait and executing it in three different query engines: Datafusion, Arrow (Acero) and DuckDB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/0*cLxvGEqSijW5f463" /><figcaption>visit <a href="https://substrait.io/">substrait.io</a></figcaption></figure><h3>Introduction</h3><blockquote><em>“All problems in computer science can be solved by another level of indirection”</em></blockquote><p>That’s what <a href="https://en.wikipedia.org/wiki/David_Wheeler_(computer_scientist)">David J. Wheeler</a> stated a while ago, and the world of data manipulation and analytical computations is no exception.</p><p>Today, data manipulation and data analysis interfaces are either coupled to their underlying execution engine (Spark, Dremio etc.) or required to generate an engine-specific compute representation for each execution engine they wish to use (<a href="https://dplyr.tidyverse.org/">dplyr</a> in R or <a href="https://ibis-project.org/ibis-for-sql-programmers/">Ibis</a> in Python). This issue is better described in the following diagram, taken from Wes McKinney’s <a href="https://www.youtube.com/watch?v=YXkyTc9mfGQ&amp;t=1238s">talk</a> [1].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kKe2vJOIsew8AV2c" /></figure><p>With that issue in mind, Substrait was designed.</p><p><strong>So, what is Substrait?</strong></p><p>Substrait is a cross-language specification for data compute operations, accompanied by a protobuf-based representation.</p><p><strong>Wait, what?</strong></p><p>In other words, Substrait is a standardized intermediate representation (IR) for query plans. It allows you to represent your query plan in a form that (ideally) any execution engine is (or will be) able to understand.</p><p>Using Substrait we can decouple the APIs from the underlying execution engines.</p><p>Following the example from the <a href="https://voltrondata.com/resources/introducing-substrait-an-interoperable-data-to-engine-connector">Voltron’s data blog</a> [2,3] you can think of it as the <a href="https://en.wikipedia.org/wiki/SWIFT">SWIFT</a> protocol, a standard for communicating between banks worldwide: each bank uses different internal systems, yet people are able to send money between banks because of the shared protocol.</p><p>By using Substrait, we can decouple API and compute layers (the same way storage has been decoupled from compute). Instead of maintaining pairwise interfaces between APIs and execution engines, the idea is to employ Substrait as the standardized interface for the backend execution engines [1,4].</p><p>The vision, again, can be seen in the following diagram, taken from the same talk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lTQkgEWeKwGkZZKw" /></figure><p>It’s time to move to some examples.</p><p>I guess that if you were asked to design a demo for Substrait on your own, you would probably want to generate a single query plan, represent it using Substrait — and execute it with three different engines. Well, great minds think alike.</p><p>But first, here’s a brief overview of the technologies we’ll be using for this demo:</p><h4><strong>Producing Substrait plan:</strong></h4><p>A “Producer” refers to software capable of generating a Substrait plan.</p><p>We’ll be using <a href="https://ibis-project.org/">Ibis</a>. Ibis allows you to write your queries in a “pythonic” way (abstraction over the various SQL dialects or other query manipulation languages), and is currently integrated with ~17 backends. It also allows you to produce a Substrait plan from your query plan!</p><h4><strong>Consuming the Substrait plan:</strong></h4><p>A “Consumer” represents software that consumes the Substrait plan and executes it against some data. <br>To consume and execute this plan, we’ll be using three different query engines:</p><ul><li><a href="https://duckdb.org/">DuckDB</a> — an in-memory analytical database management system (DBMS) that is designed to provide high performance for analytical queries</li><li><a href="https://arrow.apache.org/datafusion/">DataFusion</a> — extensible query engine for building high-quality data-centric systems in <a href="http://rustlang.org/">Rust</a></li><li><a href="https://arrow.apache.org/docs/cpp/streaming_execution.html">Acero</a> — is part of the <a href="https://arrow.apache.org/">Apache Arrow</a> project itself, and it provides a streaming query engine.</li></ul><p>These engines are “Arrow-native”, which means they use the <a href="https://arrow.apache.org/">Apache Arrow</a> in-memory format. For those who are not familiar with Arrow, it defines a standard way to represent columnar data in-memory which has a lot of benefits in terms of efficiency.</p><p>I know, it might look a bit overwhelming, but let’s see how simply it is done.</p><h3>Demo</h3><p>This demo is an extension of Gil Forsyth’s <a href="https://ibis-project.org/blog/ibis_substrait_to_duckdb/">excellent blog</a> and draws heavy inspiration from it [5].</p><p>For the purpose of this demo, we’ll be using some dummy data (thanks to chatGPT):</p><pre>import pandas as pd<br><br># Employees names are unique<br>employees_data = {<br>&#39;Name&#39;: [&#39;John&#39;, &#39;Alice&#39;, &#39;Bob&#39;, &#39;Emily&#39;, <br>         &#39;Michael&#39;, &#39;Sarah&#39;, &#39;Daniel&#39;, &#39;Emma&#39;],<br>&#39;Age&#39;: [25, 30, 35, 28, 32, 27, 31, 29],<br>&#39;City&#39;: [&#39;New York&#39;, &#39;Los Angeles&#39;, &#39;Chicago&#39;, &#39;New York&#39;, <br>         &#39;New York&#39;, &#39;Miami&#39;, &#39;Chicago&#39;, &#39;Los Angeles&#39;]<br>}<br>salaries_data = {<br>&#39;Name&#39;: [&#39;John&#39;, &#39;Alice&#39;, &#39;Bob&#39;, &#39;Emily&#39;, <br>         &#39;Michael&#39;, &#39;Sarah&#39;, &#39;Daniel&#39;, &#39;Emma&#39;],<br>&#39;Salary&#39;: [5000, 6000, 7000, 8000, 5500, 6500, 7500, 8500],<br>&#39;Department&#39;: [&#39;HR&#39;, &#39;IT&#39;, &#39;Finance&#39;, &#39;R&amp;D&#39;, <br>               &#39;IT&#39;, &#39;Finance&#39;, &#39;HR&#39;, &#39;R&amp;D&#39;]<br>}<br><br>df_employees = pd.DataFrame(employees_data)<br>                  .to_csv(&quot;employees.csv&quot;, index=False)<br>df_salaries = pd.DataFrame(salaries_data)<br>                  .to_csv(&quot;salaries.csv&quot;, index=False)</pre><h4>Producing the Substrait plan</h4><p>First, let’s setup the environment:</p><pre>conda create -n substrait-ibis-duckdb<br>conda activate substrait-ibis-duckdb<br>conda install -c conda-forge ibis-duckdb==5.1 ibis-substrait==2.19 ipython ipykernel</pre><p>Next, let’s define the “table expressions” using Ibis. It’s important to note that, at this point, Ibis is unaware of the data we created earlier. These table expressions serve as abstract declarations about the tables we intend to manipulate.</p><pre>import ibis<br>from ibis import _<br><br>employees = ibis.table(<br>    [<br>        (&quot;Name&quot;, &quot;str&quot;),<br>        (&quot;Age&quot;, &quot;int&quot;),<br>        (&quot;City&quot;, &quot;str&quot;),<br>    ],<br>    name=&quot;employees&quot;,<br>)<br><br>salaries = ibis.table(<br>    [<br>        (&quot;Name&quot;, &quot;str&quot;),<br>        (&quot;Salary&quot;, &quot;int&quot;),<br>        (&quot;Department&quot;, &quot;str&quot;),<br>    ],<br>    name=&quot;salaries&quot;,<br>)</pre><p>Now we can create a simple query plan. I admit that this query doesn’t include much logic, but it demonstrates some of the relevant operators, such as scan, filter, join, and aggregations (more on that in the arrow part).</p><pre># Get the average salary in each city, excluding the IT personas (sorry).<br># Note that &quot;Name&quot; is unique.<br># It&#39;s not optimized, on purpose (why to filter after the join?).<br>query = (<br>    employees.join(salaries, &quot;Name&quot;)<br>    .filter(_.Department != &quot;IT&quot;)<br>    .group_by(&quot;City&quot;)<br>    .agg(mean_salary = _.Salary.mean())<br>)</pre><p>If you’re interested in how Ibis composes an SQL statement from this query, you can simply type <em>ibis.show_sql(query)</em> to see the generated SQL.</p><p>Now, let’s proceed to construct a Substrait plan from this query.</p><pre><br>from ibis_substrait.compiler.core import SubstraitCompiler<br><br>compiler = SubstraitCompiler()<br>plan = compiler.compile(query)<br><br>with open(&quot;query.proto&quot;, &quot;wb&quot;) as f:<br>    f.write(plan.SerializeToString())</pre><p>You can print the plan itself and take a look at it. Additionally, you can print it in JSON format using the <em>google.protobuf</em> library.</p><p>If you want to gain a better understanding of what the Substrait plan is composed of, I recommend referring to their <a href="https://substrait.io/tutorial/sql_to_substrait/">official tutorial</a>.</p><p>Now that we have our Substrait plan, we’re ready to proceed. It’s time to put our plan to the test.</p><h4>Consuming with DuckDB</h4><p>We’ll be using the same environment we defined earlier.</p><p>First, we create a DuckDB connection and create a database with the two tables:</p><pre>import duckdb<br>from duckdb import DuckDBPyConnection<br><br>def load_tables(connection: DuckDBPyConnection):<br>    connection.execute(<br>        &quot;CREATE TABLE employees AS SELECT * FROM employees.csv&quot;<br>    )<br>    connection.execute(<br>        &quot;CREATE TABLE salaries AS SELECT * FROM salaries.csv&quot;<br>    )<br><br>duckdb_conn = duckdb.connect(database=&quot;example.db&quot;,read_only=False)<br># create the tables but avoid creating them twice<br>if not duckdb_conn.sql(&quot;SHOW TABLES&quot;):<br>    load_tables(duckdb_conn)</pre><p>Now, we just read the substrait plan and execute it!</p><pre>duckdb_conn.install_extension(&quot;substrait&quot;)<br>duckdb_conn.load_extension(&quot;substrait&quot;)<br><br>with open(&quot;query.proto&quot;, &quot;rb&quot;) as f:<br>    substrait_bytes = f.read()<br><br>result = duckdb_conn.from_substrait(substrait_bytes)<br>print(result)</pre><p>And you’ll get:</p><pre>┌─────────────┬─────────────┐<br>│    City     │ mean_salary │<br>│   varchar   │   double    │<br>├─────────────┼─────────────┤<br>│ New York    │      6500.0 │<br>│ Chicago     │      7250.0 │<br>│ Miami       │      6500.0 │<br>│ Los Angeles │      8500.0 │<br>└─────────────┴─────────────┘</pre><p>That simple.</p><h4>Consuming with Arrow (Acero)</h4><p>Let’s set up a new environment using the latest release of arrow</p><pre>conda create -n substrait-arrow-datafusion<br>conda activate substrait-arrow-datafusion<br>conda install -c conda-forge pyarrow==12.0.0</pre><p>We are now able to load the data (side note: if you haven’t played around with Arrow yet, give it a try by loading some heavy CSV files and see how fast it is).</p><pre>import pyarrow as pa<br>from pyarrow.lib import tobytes<br>import pyarrow.substrait as substrait<br>from pyarrow import csv<br>import pandas as pd<br><br>employees = pa.csv.read_csv(&quot;./employees.csv&quot;)<br>salaries = pa.csv.read_csv(&quot;./salaries.csv&quot;)</pre><p>Let’s execute it with Acero. This time we’ll need to supply a “table_provider” which is a function to resolve any “NamedTable” relation to a table (you can read more about it <a href="https://arrow.apache.org/docs/python/generated/pyarrow.substrait.run_query.html#pyarrow.substrait.run_query">here</a>).</p><pre>def table_provider(names, schema):<br>        if not names:<br>            raise Exception(&quot;No names provided&quot;)<br>        elif names[0] == &quot;employees&quot;:<br>            return employees<br>        elif names[0] == &quot;salaries&quot;:<br>            return salaries<br>        else:<br>            raise Exception(&quot;Unrecognized table name&quot;)<br><br>substrait_bytes = None<br>with open(&quot;query.proto&quot;, &quot;rb&quot;) as f:<br>    substrait_bytes = f.read()<br><br>reader = pa.substrait.run_query(<br>      substrait_bytes, table_provider=table_provider<br>)<br>result = reader.read_all().to_pandas()<br>print(result)<br># same results as DuckDB</pre><p>Note that as stated in their <a href="https://arrow.apache.org/docs/cpp/streaming_execution.html">docs</a>, Acero is still experimental and a stable API is not yet guaranteed.</p><p>In particular, if you attempt to execute a query that involves sorting the data or limiting the number of retrieved records, you will notice that these features are not currently implemented (but it’s <a href="https://github.com/apache/arrow/pull/34651">in the works</a>!).</p><h4>Consuming with DataFusion</h4><p>Finally, we’ll repeat the process using the DataFusion in-memory query engine. Note that I use its <a href="https://github.com/apache/arrow-datafusion-python">python binding</a> for the sake of simplicity (instead of Rust).</p><p>Add <em>datafusion</em> to <em>substrait-arrow-datafusion</em> environment:</p><pre>pip install datafusion</pre><p>We begin by creating a <em>SessionContext</em> and load our (dummy) data. A <a href="https://docs.rs/datafusion/latest/datafusion/execution/context/struct.SessionContext.html">SessionContext</a> is the main interface for executing queries with DataFusion, it maintains the state of the connection between a user and an instance of the DataFusion engine.</p><pre>from datafusion import SessionContext<br><br>ctx = SessionContext()<br>ctx.register_csv(<br>    &quot;employees&quot;, &quot;./employees.csv&quot;<br>)<br><br>ctx.register_csv(<br>    &quot;salaries&quot;, &quot;./salaries.csv&quot;<br>)</pre><p>Then we load the query plan and execute it:</p><pre>from datafusion import substrait as ss<br><br>substrait_bytes = None<br>with open(&quot;query.proto&quot;, &quot;rb&quot;) as f:<br>    substrait_bytes = f.read()<br><br># Deserialize the .proto file<br>substrait_plan = ss.substrait.serde.deserialize_bytes(substrait_bytes)<br># Get the query plan<br>df_logical_plan = ss.substrait.consumer.from_substrait_plan(<br>  ctx, substrait_plan<br>)<br># Execute it!<br>results = ctx.create_dataframe_from_logical_plan(df_logical_plan)<br>print(results)</pre><p>and as expected:</p><pre>+-------------+----------------------+<br>| City        | AVG(salaries.Salary) |<br>+-------------+----------------------+<br>| New York    | 6500.0               |<br>| Los Angeles | 8500.0               |<br>| Miami       | 6500.0               |<br>| Chicago     | 7250.0               |<br>+-------------+----------------------+</pre><p>Nice!</p><p>By the way, I recommend printing the <em>df_logical_plan</em>, it’s shown in a nice and concise way. At the end we’ll have a bonus section of how we can visualise the plan as a DAG as well!</p><h3>Summary &amp; Bonus</h3><p>In this article, we gave a gentle introduction to Substrait, a technology that we explore through a hands-on example. We discussed how to generate a Substrait plan and demonstrated its consumption using three different engines. If you find this topic interesting, I’d recommend Jacques Nadeau’s <a href="https://www.youtube.com/watch?v=YXnoBUQP258">talk</a> at VLDB about substrait, and Wes McKinney’s <a href="https://www.youtube.com/watch?v=YXkyTc9mfGQ&amp;t=1238s">talk</a> about Ibis, Arrow and Substrait.</p><p>Now, as a bonus, you can use <strong><em>graphivz</em></strong> to visualise the query plan! After adding it to your environment, you can display the graph in a jupyter notebook:</p><pre>from graphviz import Source<br><br>diagram = df_logical_plan.display_graphviz()<br>s = Source(diagram)<br>s # the graph will be shown, use s.view() to save it locally.</pre><p>You’ll get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/0*3bM499vvKS5MXbTy" /></figure><p>Note that when creating a Substrait plan, no optimization steps are involved. How do we see that? The Filter before the final aggregation step should have probably been pushed down towards its source. You could try it yourself! Move this filter to salaries table definition in Ibis, then remove the filtering from the query and see how the resulting plan changes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/0*opZ-SddY8TbhjVbW" /></figure><p>This is the code used:</p><pre># define salaries table. Then:<br>salaries = salaries.filter(salaries.Department != &quot;IT&quot;)<br><br>query = (<br>    employees.join(salaries, &quot;Name&quot;)<br>    .group_by(&quot;City&quot;)<br>    .agg(mean_salary = _.Salary.mean())<br>)<br><br># export to Substrait format...</pre><p>And if you are interested in query optimization, you’d probably want to take a look at <a href="https://calcite.apache.org/">Apache Calcite</a>.</p><h3>Acknowledgements</h3><p>This work was partially funded by <a href="https://www.teadal.eu/about-teadal/">EU TEADAL</a> project number 101070186.</p><p>I’m Omri Levy, a Student researcher at IBM Research (<a href="https://www.linkedin.com/in/levyomri/">linkedin</a>).</p><h3>References</h3><p>[1]<strong> </strong><a href="https://www.youtube.com/watch?v=YXkyTc9mfGQ&amp;t=1238s">https://www.youtube.com/watch?v=YXkyTc9mfGQ&amp;t=1238s</a></p><p>[2] <a href="https://voltrondata.com/resources/what-is-substrait-high-level-primer">https://voltrondata.com/resources/what-is-substrait-high-level-primer</a></p><p>[3] <a href="https://voltrondata.com/resources/introducing-substrait-an-interoperable-data-to-engine-connector">https://voltrondata.com/resources/introducing-substrait-an-interoperable-data-to-engine-connector</a></p><p>[4] <a href="https://www.youtube.com/watch?v=YXnoBUQP258&amp;t=1738s">https://www.youtube.com/watch?v=YXnoBUQP258&amp;t=1738s</a></p><p>[5] <a href="https://ibis-project.org/blog/ibis_substrait_to_duckdb/">https://ibis-project.org/blog/ibis_substrait_to_duckdb/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5dc74aeb52f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>