<?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 jboothomas on Medium]]></title>
        <description><![CDATA[Stories by jboothomas on Medium]]></description>
        <link>https://medium.com/@jboothomas?source=rss-3f68706e8d2e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*5axSpiOPtb1Kcjx74BOzog.jpeg</url>
            <title>Stories by jboothomas on Medium</title>
            <link>https://medium.com/@jboothomas?source=rss-3f68706e8d2e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 22:57:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jboothomas/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[Agentics with the Model Context Protocol and Pure Storage]]></title>
            <link>https://jboothomas.medium.com/unlocking-agentics-with-the-model-context-protocol-and-pure-storage-428a48cbac7d?source=rss-3f68706e8d2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/428a48cbac7d</guid>
            <category><![CDATA[flashblade]]></category>
            <category><![CDATA[pure-storage]]></category>
            <category><![CDATA[model-context-protocol]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[jboothomas]]></dc:creator>
            <pubDate>Tue, 21 Jan 2025 12:33:09 GMT</pubDate>
            <atom:updated>2025-01-30T09:23:54.971Z</atom:updated>
            <content:encoded><![CDATA[<p>This is part 2 of my blog series on integrating Pure Storage on-premises full flash arrays with the Claude.ai Model Context Protocol. In part 1 — <a href="https://jboothomas.medium.com/unlocking-on-premise-storage-potential-with-the-model-context-protocol-mcp-90c67e72f14d">see here</a>- I covered the code required to create the basic integration allowing for hardcoded calls from the MCP tools to a given array, but I want to be able to to take actions as well as retrieve information and not end up with one MCP tool per request.</p><p>To accomplish the above I need to change from a hardcoded restAPI endpoint call on the storage array within the MCP server tool, like get_arrays used in part 1 blog’ pure-info implementation, to a modular approach where it accepts any endpoint call as a parameter. The following code implements this and when setup it provides a single ‘pure-fb’ agent:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eomgZkmBEIB1jkV1N5ce6g.png" /></figure><h4>Code</h4><p>Here is the modified code that allows us to pass queries with parameters against a given array identified by host and api-token. The new MCP server tool is named pure-fb and currently leverages token authorization. The full code can be found in my <a href="https://github.com/jboothomas/pure-model-context-protocol/tree/main">github repository</a>:</p><pre>import asyncio<br><br>from mcp.server.models import InitializationOptions<br>import mcp.types as types<br>from mcp.server import NotificationOptions, Server<br>from pydantic import AnyUrl<br>import mcp.server.stdio<br><br>import json<br>import pypureclient<br>from pypureclient import flashblade<br><br>from datetime import datetime, timedelta<br><br>server = Server(&quot;pure-mcp-server&quot;)<br><br>class FlashbladeClient:<br>    &quot;&quot;&quot;<br>    A client for interacting with Pure Storage Flashblade REST API 2.0<br>    &quot;&quot;&quot;<br>    <br>    def __init__(self, fb_host, fb_api_token):<br>        &quot;&quot;&quot;<br>        Initialize the Flashblade client<br>        <br>        Args:<br>            fb_host (str): The hostname or IP address of the Flashblade<br>            fb_api_token (str): The API token for authentication<br>        &quot;&quot;&quot;<br>        try:<br>            self.client = flashblade.Client(target=fb_host, api_token=fb_api_token, verify_ssl=False, user_agent=&#39;MCP/0.1.0&#39;)<br>        except pypureclient.exceptions.PureError as e:<br>            print(f&quot;Exception when logging in to the array: {e}&quot;)<br><br>    def call_endpoint(self, method_name, **kwargs):<br>        &quot;&quot;&quot;<br>        Calls a method on the underlying flashblade.Client object by name.<br><br>        Args:<br>            method_name (str): The name of the method to call on the client.<br>            **kwargs: Any keyword arguments to pass to that method.<br><br>        Returns:<br>            The result of the underlying client method call, or None on error.<br>        &quot;&quot;&quot;<br>        try:<br>            method = getattr(self.client, method_name)<br>            return method(**kwargs)<br>        except pypureclient.exceptions.PureError as e:<br>            print(f&quot;Exception with {method_name}: {e}&quot;)<br>            return None<br>        except AttributeError:<br>            print(f&quot;Method &#39;{method_name}&#39; not found on flashblade.Client&quot;)<br>            return None<br><br><br>def json_log(response, endpoint_name):<br>    &quot;&quot;&quot;<br>    Serializes and logs the response from a Flashblade API endpoint.<br><br>    Args:<br>        response: The API response to be logged and serialized.<br>        endpoint_name (str): The name of the API endpoint.<br><br>    Returns:<br>        str: JSON-formatted string of the response data.<br>    &quot;&quot;&quot;<br>    if isinstance(response, pypureclient.responses.ValidResponse):<br>        if response and hasattr(response, &quot;items&quot;):<br>            json_data = json.dumps([item.to_dict() for item in response.items])<br>        else:<br>            json_data = json.dumps({&quot;error&quot;: f&quot;No data available for {endpoint_name}&quot;})<br>    else:<br>        json_data = json.dumps({&quot;error&quot;: f&quot;Invalid response from {endpoint_name}&quot;})<br><br>    server.request_context.session.send_log_message(<br>        level=&quot;info&quot;,<br>        data=f&quot;{endpoint_name}: {json_data}&quot;<br>    )<br>    return json_data<br><br>### MCP tools ###<br>@server.list_tools()<br>async def handle_list_tools() -&gt; list[types.Tool]:<br>    &quot;&quot;&quot;<br>    List available tools.<br>    Each tool specifies its arguments using JSON schema validation.<br>    &quot;&quot;&quot;<br>    return [<br>        types.Tool(<br>            name=&quot;pure-fb&quot;,<br>            description=&quot;Run a command against a given FlashBlade&quot;,<br>            inputSchema={<br>                &quot;type&quot;: &quot;object&quot;,<br>                &quot;properties&quot;: {<br>                    &quot;host&quot;: {&quot;type&quot;: &quot;string&quot;, &quot;description&quot;: &quot;IP address of array management endpoint&quot;},<br>                    &quot;api_token&quot;: {&quot;type&quot;: &quot;string&quot;, &quot;description&quot;: &quot;API token for array management user&quot;},<br>                    &quot;command&quot;: {&quot;type&quot;: &quot;string&quot;, &quot;description&quot;: &quot;SDK call to run against the array&quot;},<br>                    &quot;parameters&quot;: {<br>                        &quot;type&quot;: &quot;object&quot;,<br>                        &quot;description&quot;: &quot;Optional parameters to pass to the SDK call&quot;,<br>                        &quot;additionalProperties&quot;: True<br>                    }<br>                },<br>                &quot;required&quot;: [&quot;host&quot;, &quot;api_token&quot;, &quot;command&quot;],<br>            },<br>        ),<br>    ]<br><br><br>@server.call_tool()<br>async def handle_call_tool(name: str, arguments: dict | None) -&gt; list[types.TextContent | types.ImageContent | types.EmbeddedResource]:<br>    &quot;&quot;&quot;<br>    Handle tool execution requests.<br>    &quot;&quot;&quot;<br>    if name not in [&quot;pure-fb&quot;]:<br>        raise ValueError(f&quot;Unknown tool: {name}&quot;)<br><br>    if not arguments:<br>        raise ValueError(&quot;Missing arguments&quot;)<br><br>    query_host = arguments.get(&quot;host&quot;)<br>    query_api_token = arguments.get(&quot;api_token&quot;)<br><br>    server.request_context.session.send_log_message(<br>        level=&quot;info&quot;,<br>        data=f&quot;Initializing query with &#39;{query_host}&#39; and &#39;{query_api_token}&#39;&quot;,<br>    )<br><br>    if not query_host or not query_api_token:<br>        raise ValueError(&quot;Missing host or api_token&quot;)<br><br>    # Init array client<br>    fb_client = FlashbladeClient(fb_host=query_host, fb_api_token=query_api_token)<br><br>    if name == &quot;pure-fb&quot;:<br>        query_command = arguments.get(&quot;command&quot;)<br>        query_parameters = arguments.get(&quot;parameters&quot;, {})<br><br>        if not query_command:<br>            raise ValueError(&quot;Missing command&quot;)<br><br>        try:<br>            response = fb_client.call_endpoint(query_command, **query_parameters)<br>            response_info = json_log(response, query_command)<br>            return [types.TextContent(type=&quot;text&quot;, text=f&quot;{response_info}&quot;)]<br>        except Exception as error:<br>            return types.CallToolResult(<br>                isError=True,<br>                content=[types.TextContent(type=&quot;text&quot;, text=f&quot;Error: {str(error)}&quot;)]<br>            )<br><br>async def main():<br>    async with mcp.server.stdio.stdio_server() as (read_stream, write_stream):<br>        await server.run(<br>            read_stream,<br>            write_stream,<br>            InitializationOptions(<br>                server_name=&quot;pure-mcp-server&quot;,<br>                server_version=&quot;0.1.0&quot;,<br>                capabilities=server.get_capabilities(<br>                    notification_options=NotificationOptions(),<br>                    experimental_capabilities={},<br>                ),<br>            ),<br>        )</pre><h4>Usage</h4><p>With our new MCP server in place I can run informational queries such as :</p><p>“use pure-fb on host: 1.2.3.4 with api-token: T-7c7a*****f23e to run the command: get_file_systems and then the command: get_buckets. Sort the items per used size and indicate for each if it is a bucket by tagging the item as ‘s3’ or a file system by tagging the item as ‘fs’. Make sure to correctly sort by descending order based on used size and list the top 5 by used space.”</p><p>This results in the following output:</p><pre>I&#39;ll help you retrieve and analyze the file systems and buckets information <br>from your FlashBlade.<br>View result from pure-fb from pureflashblade (local){}<br>View result from pure-fb from pureflashblade (local){}<br><br>Here are the top 5 storage items (combining both file systems and buckets) <br>sorted by used space in descending order:<br>lbo-outscale-perfs [fs]: 7,240,575,042,227 bytes (7.24 TB)<br>lbo-vertica [fs]: 3,311,892,804,361 bytes (3.31 TB)<br>dm [fs]: 2,213,617,471,583 bytes (2.21 TB)<br>lbo-hdf5 [fs]: 1,643,315,388,928 bytes (1.64 TB)<br>eg-px-share01 [fs]: 869,598,847,641 bytes (869.6 GB)<br>As we can see, the top 5 spots are all occupied by file systems, with the <br>largest being lbo-outscale-perfs at 7.24 TB. For reference, the largest <br>bucket (cvlt-uklab-object-lock at 265.1 GB) would rank much lower in this <br>combined list.</pre><p>This is similar to what I showed in part 1 but the modular approach now allows me to query any endpoint (get arrays, buckets, file systems,…). This modular approach also enables calling endpoints to take actions on the array, for this I will run a simple create bucket command using the following query:</p><p>“use pure-fb on host: 1.2.3.4 with api-token: T-7c7a*****f23e and the command post_buckets with the parameters: names=[“jbtmcptest”], bucket=BucketPost(account=Reference(name=’jbt’)) ”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g_D66lfa4Y0G9Cw__QIJGA.png" /></figure><p>On the Pure Storage FlashBlade array the relevant bucket is now present:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sg4rRQPoJx4AycQxIL_TLg.png" /></figure><p>and an example query to create a file system, note that in this example I let the LLM figure out the actual command:</p><p>“create a file system using the following parameters: names=[“jbt-myfs”], file_system=FileSystemPost(provisioned=5000, hard_limit_enabled=True, nfs=Nfs(v4_1_enabled=True), smb=Smb(enabled=True), multi_protocol=MultiProtocolPost(access_control_style=”nfs”))”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aNOpOQ2ontZSMnVu2q9kxA.png" /></figure><p>We can see that ClaudeAI was able to provide the correct command ‘post_file_system’ to run this request !</p><h4>Agent</h4><p>I will now add some context to my chat and define the behaviour and capabilities of a storage agent that has two arrays to control:</p><p>“You are a smart storage management agent that via the pure-fb tool can manage the following two arrays:</p><p>array01 at host: 1.2.3.4 with api-token: T-7c7a*****f23e</p><p>array02 at host: 1.2.3.5 with api-token: T-f2e0*****3b8d”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1pWeRffFczNQ_Ib_uZ8ztA.png" /></figure><p>With this storage agent defined I can run queries against both arrays such as:</p><p>“Get all buckets from both arrays, extract name, raw total_used space, and source array into a single list. Sort strictly based on the raw total_used values without any conversions. Provide the top 15 from the list and convert used space to appropriate units for display.”</p><p>Our agent starts by gathering the relevant data using get_buckets and get_file_systems against the two arrays:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tiRmUvCuDR5UzZUIXB_SiA.png" /></figure><p>Then the agent proceeds to sort the buckets by used space as requested. Note that it took several attempts to get the prompt for the sorting to be correct.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PuYjaMeR2mrtFTo3w0v7cw.png" /></figure><h4>Conclusion</h4><p>With our Model Context Protocol server we enabled natural language integration between an on-premises Pure Storage array and our LLM, to run queries and take actions.</p><p>Agentics is enabling the “new possible” and will drive an interesting next couple of years !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=428a48cbac7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking On-Premises Storage Potential with the Model Context Protocol (MCP)]]></title>
            <link>https://jboothomas.medium.com/unlocking-on-premise-storage-potential-with-the-model-context-protocol-mcp-90c67e72f14d?source=rss-3f68706e8d2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/90c67e72f14d</guid>
            <category><![CDATA[pure-storage]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[flashblade]]></category>
            <category><![CDATA[model-context-protocol]]></category>
            <dc:creator><![CDATA[jboothomas]]></dc:creator>
            <pubDate>Fri, 10 Jan 2025 11:01:25 GMT</pubDate>
            <atom:updated>2025-01-29T18:15:08.674Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s data-driven landscape, efficient and secure storage management is critical for enterprises handling vast amounts of information. Reporting and collecting information to understand our data footprint has long been a tedious task, but what if we could leverage a natural language interface to query information from our hardware to facilitate insights, and if wanted expand this capability into taking actions.</p><p>MCP is an open protocol that standardises how applications provide context to LLMs. This blog will cover the steps to build an MCP server to query Pure Storage arrays (FlashBlade specifically), from within Claude desktop and get a natural language response as per this screenshot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sWfcBGXJ-mrxozOmGp-bdg.png" /></figure><h4>Code</h4><p>First step is to install the uv python package manager, the official guide is here: <a href="https://docs.astral.sh/uv/getting-started/installation/#installation-methods">https://docs.astral.sh/uv/getting-started/installation/#installation-methods</a> on my macbook I used brew:</p><pre>% brew install uv</pre><p>Next we need to create the MCP server structure, for this we will make use of the provided tools: uvx create-mcp-server.</p><pre>% uvx create-mcp-server     <br>Creating a new MCP server project using uv.<br>This will set up a Python project with MCP dependency.<br><br>Let&#39;s begin!<br><br>Project name (required): pure-mcp-server<br>Project description [A MCP server project]: A MCP server to retrieve realtime information from a Pure Storage FlashBlade<br>Project version [0.1.0]: <br>Project will be created at: /Users/jthomas/mcp/pure-mcp-server<br>Is this correct? [Y/n]: Y<br>....<br>Claude.app detected. Would you like to install the server into Claude.app now? [Y/n]: Y<br><br>✅ Added pure-mcp-server to Claude.app configuration<br>Settings file location: /Users/jthomas/Library/Application Support/Claude/claude_desktop_config.json<br>✅ Created project pure-mcp-server in pure-mcp-server<br>ℹ️ To install dependencies run:<br>   cd pure-mcp-server<br>   uv sync --dev --all-extras</pre><p>Proceed with the final steps to install dependencies and our skeleton MCP server is ready. The source code that we need to modify is located under pure-mcp-server/src/pure-mcp-server at this point the code is for the template add-notes MCP server, we will now modify that so as to integrate with an onpremise Pure Storage FlashBlade array.</p><p>From the project folder I enter into the python virtual environment that was automatically created by uv.</p><pre>% source .venv/bin/activate<br>(pure-mcp-server) %</pre><p>Then, install the pure storage python SDK, as I will leverage this to interact with the FlashBlade restAPI.</p><pre>% uv pip install py-pure-client</pre><p>Within the src/pure-mcp-server/server.py file I add this library to our import section :</p><pre>import asyncio<br><br>from mcp.server.models import InitializationOptions<br>import mcp.types as types<br>from mcp.server import NotificationOptions, Server<br>from pydantic import AnyUrl<br>import mcp.server.stdio<br><br>import json<br>import pypureclient<br>from pypureclient import flashblade<br>from datetime import datetime, timedelta<br><br>server = Server(&quot;pure-mcp-server&quot;)</pre><p>Then I create a FlashBlade class to hold all the SDK calls that we will call to from the MCP tool definitions. To simplify the code, I am using a call_endpoint definition to pass the relevant restAPI endpoint as required.</p><pre>class FlashbladeClient:<br>    &quot;&quot;&quot;<br>    A client for interacting with Pure Storage Flashblade REST API 2.0<br>    &quot;&quot;&quot;<br>    <br>    def __init__(self, fb_host, fb_api_token):<br>        &quot;&quot;&quot;<br>        Initialize the Flashblade client<br>        <br>        Args:<br>            host (str): The hostname or IP address of the Flashblade<br>            api_token (str): The API token for authentication<br>            verify_ssl (bool): Whether to verify SSL certificates<br>        &quot;&quot;&quot;<br>        try:<br>            # login to the array with your API_TOKEN<br>            self.client = flashblade.Client(target=fb_host, api_token=fb_api_token, verify_ssl=False, user_agent=&#39;MCP/0.1.0&#39;)<br>        except pypureclient.exceptions.PureError as e:<br>            print(&quot;Exception when logging in to the array: %s\n&quot; % e)<br><br>    def call_endpoint(self, method_name, **kwargs):<br>        &quot;&quot;&quot;<br>        Calls a method on the underlying flashblade.Client object by name,<br>        catching and logging any PureError exceptions.<br><br>        Args:<br>            method_name (str): The name of the method to call on the client.<br>                               (e.g., &#39;get_admins&#39;, &#39;get_alert_watchers&#39;, etc.)<br>            **kwargs: Any keyword arguments to pass to that method.<br><br>        Returns:<br>            The result of the underlying client method call, or None on error.<br>        &quot;&quot;&quot;<br>        try:<br>            method = getattr(self.client, method_name)<br>            return method(**kwargs)<br>        except pypureclient.exceptions.PureError as e:<br>            print(f&quot;Exception with {method_name}: {e}&quot;)<br>            return None<br>        except AttributeError:<br>            print(f&quot;Method &#39;{method_name}&#39; not found on flashblade.Client&quot;)<br>            return None<br><br>    # Example usage:<br>    # fb_client = FlashbladeClient(&quot;1.2.3.4&quot;, &quot;your_api_token&quot;)<br>    # response = fb_client.call_endpoint(&quot;get_admins&quot;, username=&quot;pureuser&quot;, expose_api_token=True)</pre><p>I added a helper function to streamline the api response to json output:</p><pre><br>def json_log(response, endpoint_name):<br>    &quot;&quot;&quot;<br>    Serializes and logs the response from a Flashblade API endpoint.<br><br>    Args:<br>        response: The API response to be logged and serialized.<br>        endpoint_name (str): The name of the API endpoint.<br><br>    Returns:<br>        str: JSON-formatted string of the response data.<br>    &quot;&quot;&quot;<br>    # Validate response type<br>    if isinstance(response, pypureclient.responses.ValidResponse):<br>        # Check if the response has items and serialize them<br>        if response and hasattr(response, &quot;items&quot;):<br>            json_data = json.dumps([item.to_dict() for item in response.items])<br>        else:<br>            json_data = json.dumps({&quot;error&quot;: f&quot;No data available for {endpoint_name}&quot;})<br>    else:<br>        json_data = json.dumps({&quot;error&quot;: f&quot;Invalid response from {endpoint_name}&quot;})<br><br>    # Log the data<br>    server.request_context.session.send_log_message(<br>        level=&quot;info&quot;,<br>        data=f&quot;{endpoint_name}: {json_data}&quot;<br>    )<br><br>    return json_data</pre><p>Within the tools section I define the MCP “tools” that we will be able to run later from within Claude desktop app to the MCP server:</p><pre>@server.list_tools()<br>async def handle_list_tools() -&gt; list[types.Tool]:<br>    &quot;&quot;&quot;<br>    List available tools.<br>    Each tool specifies its arguments using JSON schema validation.<br>    &quot;&quot;&quot;<br>    return [<br>        types.Tool(<br>            name=&quot;get-array&quot;,<br>            description=&quot;Get array information&quot;,<br>            inputSchema={<br>                &quot;type&quot;: &quot;object&quot;,<br>                &quot;properties&quot;: {<br>                    &quot;host&quot;: {<br>                        &quot;type&quot;: &quot;string&quot;,<br>                        &quot;description&quot;: &quot;IP address of array management endpoint&quot;,<br>                    },<br>                    &quot;api_token&quot;: {<br>                        &quot;type&quot;: &quot;string&quot;,<br>                        &quot;description&quot;: &quot;API token for array management user&quot;,<br>                    },<br>                },<br>                &quot;required&quot;: [&quot;host&quot;,&quot;api_token&quot;],<br>            },<br>        ),<br>        types.Tool(<br>            name=&quot;get-array-full&quot;,<br>            description=&quot;Get array information, space and 7 days performance&quot;,<br>            inputSchema={<br>                &quot;type&quot;: &quot;object&quot;,<br>                &quot;properties&quot;: {<br>                    &quot;host&quot;: {<br>                        &quot;type&quot;: &quot;string&quot;,<br>                        &quot;description&quot;: &quot;IP address of array management endpoint&quot;,<br>                    },<br>                    &quot;api_token&quot;: {<br>                        &quot;type&quot;: &quot;string&quot;,<br>                        &quot;description&quot;: &quot;API token for array management user&quot;,<br>                    },<br>                },<br>                &quot;required&quot;: [&quot;host&quot;,&quot;api_token&quot;],<br>            },<br>        ),<br>    ]</pre><p>I then handle the call to each tool definition, I have only added two simple calls but the example framework provides an easy method to add whatever calls/tools are needed:</p><pre>@server.call_tool()<br>async def handle_call_tool(<br>    name: str, arguments: dict | None<br>) -&gt; list[types.TextContent | types.ImageContent | types.EmbeddedResource]:<br>    &quot;&quot;&quot;<br>    Handle tool execution requests.<br>    Tools can modify server state and notify clients of changes.<br>    &quot;&quot;&quot;<br>    if name not in [&quot;get-array&quot;, &quot;get-array-full&quot;]:<br>        raise ValueError(f&quot;Unknown tool: {name}&quot;)<br><br>    if not arguments:<br>        raise ValueError(&quot;Missing arguments&quot;)<br><br>    query_host = arguments.get(&quot;host&quot;)<br>    query_api_token = arguments.get(&quot;api_token&quot;)<br><br>    server.request_context.session.send_log_message(<br>        level=&quot;info&quot;,<br>        data=f&quot;initialize query with &#39;{query_host}&#39; and &#39;{query_api_token}&#39;&quot;,<br>    )<br><br>    if not query_host or not query_api_token:<br>        raise ValueError(&quot;Missing host or api_token&quot;)<br><br>    # Init array client<br>    fb_client = FlashbladeClient( <br>        fb_host=query_host,<br>        fb_api_token=query_api_token<br>    )<br><br>    if name == &quot;get-array&quot;:<br>        try:<br>            arrays_info_response = fb_client.call_endpoint(&quot;get_arrays&quot;)<br>            arrays_info = json_log(arrays_info_response, &quot;get_arrays&quot;)<br><br><br>            return [<br>                types.TextContent(<br>                    type=&quot;text&quot;,<br>                    text=f&quot;Arrays information: {arrays_info}&quot;<br>                )<br>            ]<br>        except Exception as error:<br>            return types.CallToolResult(<br>                isError=True,<br>                content=[<br>                    types.TextContent(<br>                        type=&quot;text&quot;,<br>                        text=f&quot;Error: {str(error)}&quot;<br>                    )<br>                ]<br>            )<br>    <br>    elif name == &quot;get-array-full&quot;:<br>        try:<br>            arrays_info_response = fb_client.call_endpoint(&quot;get_arrays&quot;)<br>            arrays_info = json_log(arrays_info_response, &quot;get_arrays&quot;)<br><br>            arrays_space_response = fb_client.call_endpoint(&quot;get_arrays_space&quot;)<br>            arrays_space = json_log(arrays_space_response, &quot;get_arrays_space&quot;)<br>            <br>            # Set the current time in epoch format (milliseconds)<br>            e_end_time = int(datetime.now().timestamp() * 1000)<br><br>            # Set the start time to 7 days before the current time in epoch format (milliseconds)<br>            e_start_time = int((datetime.now() - timedelta(days=7)).timestamp() * 1000)<br><br>            # Define the resolution in milliseconds<br>            #e_resolution = 30000 * 1000  # converting 30,000 seconds to milliseconds<br>            <br>            # Corrected call with arguments passed explicitly<br>            arrays_performance_response = fb_client.call_endpoint(<br>                &quot;get_arrays_performance&quot;, <br>                start_time=e_start_time, <br>                end_time=e_end_time<br>            )<br>            arrays_performance = json_log(arrays_performance_response, &quot;get_arrays_performance&quot;)<br><br>            # Return results as MCP JSON content<br>            return [<br>                types.TextContent(<br>                    type=&quot;text&quot;,<br>                    text=f&quot;Arrays information: {arrays_info}, space: {arrays_space}, and performance: {arrays_performance}&quot;<br>                )<br>            ]<br>        except Exception as error:<br>            return types.CallToolResult(<br>                isError=True,<br>                content=[<br>                    types.TextContent(<br>                        type=&quot;text&quot;,<br>                        text=f&quot;Error: {str(error)}&quot;<br>                    )<br>                ]<br>            )</pre><p>Then at last the main definition:</p><pre>async def main():<br>    # Run the server using stdin/stdout streams<br>    async with mcp.server.stdio.stdio_server() as (read_stream, write_stream):<br>        await server.run(<br>            read_stream,<br>            write_stream,<br>            InitializationOptions(<br>                server_name=&quot;pure-mcp-server&quot;,<br>                server_version=&quot;0.1.0&quot;,<br>                capabilities=server.get_capabilities(<br>                    notification_options=NotificationOptions(),<br>                    experimental_capabilities={},<br>                ),<br>            ),<br>        )</pre><p>The __init__.py file contents is:</p><pre>from . import server<br>import asyncio<br>import mcp.server.stdio<br><br>def main():<br>    &quot;&quot;&quot;Main entry point for the package.&quot;&quot;&quot;<br>    # Run both WebSocket and STDIO servers concurrently<br>    asyncio.run(server.main())<br><br># Optionally expose other important items at package level<br>__all__ = [&#39;main&#39;, &#39;server&#39;]</pre><p>The MCP server was added automatically to Claude desktop during the initialisation phase, to verify open the following file and check the entry is correct:</p><pre>cat /Users/jthomas/Library/Application\ Support/Claude/claude_desktop_config.json<br>{<br>  &quot;mcpServers&quot;: {<br>     &quot;pure-mcp-server&quot;: {<br>      &quot;command&quot;: &quot;uv&quot;,<br>      &quot;args&quot;: [<br>        &quot;--directory&quot;,<br>        &quot;/path/to/folder/pure-mcp-server&quot;,<br>        &quot;run&quot;,<br>        &quot;pure-mcp-server&quot;<br>      ]<br>    }<br>  }<br>}</pre><p>In addition to the MCP inspector I used the following script to validate:</p><pre>import asyncio<br>from mcp.client.session import ClientSession<br>from mcp.client.stdio import StdioServerParameters, stdio_client<br><br><br>async def main():<br>    async with stdio_client(<br>        StdioServerParameters(command=&quot;uv&quot;, args=[&quot;--directory&quot;, &quot;/Users/jthomas/mcp/pure-mcp-server&quot;, &quot;run&quot;, &quot;pure-mcp-server&quot;])<br>    ) as (read, write):<br>        async with ClientSession(read, write) as session:<br>            await session.initialize()<br><br>            # List available tools<br>            tools = await session.list_tools()<br>            print(tools)<br><br>            # Call the fetch tool<br>            result = await session.call_tool(&quot;get-array&quot;, {&quot;host&quot;: &quot;1.2.3.4&quot;, &quot;api_token&quot;: &quot;T-da03****1a98&quot;})<br>            print(result)<br><br><br>asyncio.run(main())</pre><p>This code correctly lists my MCP server tools, and also connects to the remote array, performs the necessary api call and returns the relevant json string.</p><p>Now I can via the Claude desktop app run queries using the MCP server tools against a given Pure Storage FlashBlade:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hx-87HDGxpPWJDXyxEa1zA.png" /></figure><p>and using the get-array-full tool to ask about storage space specifics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uiMl5OZTVfcQgxo5M93Hxw.png" /></figure><p>follow up questions can be asked such as : “create a graph to show the last 7 days performance based on the per metric epoch time value. Convert epoch and group performance results per day”. Note this is a pretty idle lab array:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*096dn7dHZ3o2nC5O2tGV_A.png" /></figure><h4>Conclusion</h4><p>The Claude.ai model context protocol provides an interesting approach to integrate systems into LLMs. The above example showed how simple it was to create an MCP server that pulls information from a Pure Storage Flashblade and uses the LLM to process the returned data. The MCP server could be expanded upon to include tools that take actions, opening the door to LLM based array management via a conversational interface.</p><p>Stay tuned for a future blog where I will cover that angle!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90c67e72f14d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analytics with no RDBMS brakes on!]]></title>
            <link>https://jboothomas.medium.com/analytics-with-no-rdbms-brakes-on-d07adb6cc8ab?source=rss-3f68706e8d2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d07adb6cc8ab</guid>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[sqoop]]></category>
            <category><![CDATA[spark]]></category>
            <dc:creator><![CDATA[jboothomas]]></dc:creator>
            <pubDate>Thu, 26 Dec 2024 14:59:38 GMT</pubDate>
            <atom:updated>2024-12-26T14:59:38.606Z</atom:updated>
            <content:encoded><![CDATA[<p>A good friend brought up a problem the other day that tweaked my curiosity. I decided to tackle the issue and see if a simple solution was available. How to perform cross database dump queries and collate the results into a single response, on an object oriented storage layer.</p><p>The base idea here is to remove the restrictions of the RDBMs and perform OLAP, ad-hoc queries, and potential machine learning on the data via a <a href="https://blog.purestorage.com/fast-object-storage-flashblade/">fast object storage layer</a>. Freeing up resources by running in-depth analytics/ML jobs outside of the RDBMs environment.</p><p>Our data flow is as per the below diagram. Using Sqoop I import tables from two separate Oracle databases to avro file format. I then use spark to import the avro files and perform analytics, so as to provide the collated result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3B6RMVxAHBWOE9ga" /></figure><p>Skip to the <a href="https://youtu.be/X32oMpyLOMM">video</a> if you just want to see it in action, note that for this implementation I used the following versions:</p><ul><li>Sqoop : v1.4.7</li><li>Hadoop : v2.7.3</li><li>Spark: v2.4.4</li><li>Oracle: v12</li><li>Jupyter notebook core: v4.6.0</li></ul><p>The following Sqoop job imports the database table in avro format to my S3 storage:</p><pre>sqoop import -Dmapreduce.job.user.classpath.first=true --connect jdbc:oracle:thin:@oracle1:1521:orcl1 --username myuser --password mypassword --table USERSTABLE --target-dir s3a://oracleavro/todaysdump/USERS/ --num-mappers 10 --split-by user_id --as-avrodatafile --compression-codec snappy</pre><p>I perform the same for my second oracle database table to have them both available on my shared fast object storage, we can list the contents of each output folder, here is the ‘maint’ table file output:</p><pre>hadoop fs -ls s3a://oracleavro/todaysdump/MAINT</pre><pre>s3a://oracleavro/todaysdump/MAINT/_SUCCESS<br>s3a://oracleavro/todaysdump/MAINT/part-m-00000.avro<br>s3a://oracleavro/todaysdump/MAINT/part-m-00001.avro<br>s3a://oracleavro/todaysdump/MAINT/part-m-00002.avro<br>s3a://oracleavro/todaysdump/MAINT/part-m-00003.avro<br>s3a://oracleavro/todaysdump/MAINT/part-m-00004.avro<br>s3a://oracleavro/todaysdump/MAINT/part-m-00005.avro<br>s3a://oracleavro/todaysdump/MAINT/part-m-00006.avro<br>s3a://oracleavro/todaysdump/MAINT/part-m-00007.avro<br>s3a://oracleavro/todaysdump/MAINT/part-m-00008.avro<br>s3a://oracleavro/todaysdump/MAINT/part-m-00009.avro</pre><p>From within my jupyter notebook I use the following code to import each avro file as a spark DF:</p><pre>from pyspark.sql import SparkSession<br>import pyspark</pre><pre>## CONSTANTS<br>APP_NAME = &quot;AvroSpark Application&quot;<br>AVROUSERS = &#39;s3a://oracleavro/todaysdump/USERS/*.avro&#39;<br>AVROMAINT = &#39;s3a://oracleavro/todaysdump/MAINT/*.avro&#39;</pre><pre>## Main functionality<br>spark = SparkSession.builder.appName(APP_NAME).getOrCreate()<br>usersDF = spark.read.format(&quot;avro&quot;).load(AVROUSERS)</pre><pre>maintDF = spark.read.format(&quot;avro&quot;).load(AVROMAINT)</pre><p>I can check run a simple query on each dataframe:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/0*XMrLf8axPxuvHALO" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/0*01MZFXv67aoo1M65" /></figure><p>My random generated data from the source Oracle databases is showing correctly. I can now join the data to get a ‘consolidated’ view of our tables:</p><pre>filterusers = usersDF.filter(&quot;NAME = &#39;jbthomas&#39;&quot;)</pre><pre>filtermaint = maintDF.filter(&quot;NAME = &#39;jbthomas&#39;&quot;)</pre><pre>results = filtermaint.crossJoin(filterusers)</pre><pre>results.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/0*VlRDvRfcwBdK8Cqu" /></figure><p>Check out the following video to see all this in action :</p><p><a href="https://www.youtube.com/watch?v=X32oMpyLOMM&amp;feature=youtu.be">https://youtube.com/FX32oMpyLOMM</a></p><p>That was easy!</p><p>In this example I am dumping small 1000 row tables and performing a single query. If I had a larger dataset, Sqoop provides parameters to increase the parallelism of the import. As per the <a href="https://sqoop.apache.org/docs/1.4.6/SqoopUserGuide.html#_controlling_parallelism">documentation</a>: “You can specify the number of map tasks (parallel processes) to use to perform the import by using the -m or — num-mappers argument. Each of these arguments takes an integer value which corresponds to the degree of parallelism to employ.”</p><p>To test Sqoop parallelism I ran an import of a 35GB table on a small 5 node cloudera cluster:</p><ul><li>— num-mappers 1 =&gt; import job took 4hrs 19min</li><li>— num-mappers 3 =&gt; import job took 1hr 15min</li><li>— num-mappers 9 =&gt; import job took 27min</li></ul><p>Once again using an S3 layer built for concurrency and parallelism impacts our Sqoop and Spark jobs time to result. Please read my post ‘<a href="https://www.linkedin.com/pulse/data-pipelines-does-storage-matter-jean-baptiste-thomas/">data pipelines does storage matter</a>’ to see the impact storage has on such workloads.</p><p><em>note: This is an import of a linkedin article I wrote</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d07adb6cc8ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MetaFlow AI data preparation on S3]]></title>
            <link>https://jboothomas.medium.com/metaflow-ai-data-preparation-on-s3-c0708bda12cd?source=rss-3f68706e8d2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0708bda12cd</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[pure-storage]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[metaflow]]></category>
            <category><![CDATA[flashblade]]></category>
            <dc:creator><![CDATA[jboothomas]]></dc:creator>
            <pubDate>Tue, 24 Dec 2024 12:44:46 GMT</pubDate>
            <atom:updated>2024-12-24T12:44:46.472Z</atom:updated>
            <content:encoded><![CDATA[<p>When working with AI, three critical factors come into play: model parameters/architecture, compute resources, and data. These dimensions collectively influence the accuracy of your models:</p><ul><li>Larger or better-designed models</li><li>Longer training durations or more powerful computation</li><li>Larger datasets or better-prepared data</li></ul><p>The quality of your dataset significantly affects both the model’s accuracy and the training time. For example, I recently trained a “small language model” without preprocessing the text dataset, and the results were poor, to say the least. The model produced outputs like French words mixed with English or single letters. This happened because I skipped data cleaning intentionally to evaluate the impact of unprocessed datasets — and it clearly highlighted the importance of proper data preparation.</p><p>Today, I’ll walk you through the initial data preparation steps for handling large datasets stored on S3. We’ll be using MetaFlow, a tool that simplifies the implementation of task-specific workflows.</p><h3>Metaflow code</h3><p>To access data on S3, we need an access_key_id and a secret_access_key associated with our S3 account. Since I’m working with an on-premise Pure Storage FlashBlade S3 storage solution, I also need to specify the endpoint URL.</p><p>Additionally, I’ll leverage MetaFlow’s Kubernetes integration to scale the parallelism for specific tasks.</p><p>For clarity, I’ve divided the code into sections to explain each part. However, the entire code is executed as a single block within a unique Jupyter Notebook cell.</p><h4>Imports and Parameters</h4><pre>import os<br>from metaflow import FlowSpec, step, pypi, NBRunner, kubernetes, S3<br><br># Set environment variables for metaflow kubernetes<br>os.environ[&#39;KUBECONFIG&#39;] = &#39;/home/pureuser/.metaflowconfig/config&#39;<br>os.environ[&#39;METAFLOW_KUBERNETES_NAMESPACE&#39;]= &#39;default&#39;<br><br># Set environment variables for S3 metaflow task artefacts<br>os.environ[&#39;METAFLOW_DATASTORE&#39;]= &#39;s3&#39;<br>os.environ[&#39;METAFLOW_DEFAULT_ENVIRONMENT&#39;] = &#39;pypi&#39;<br>os.environ[&#39;METAFLOW_DATASTORE_SYSROOT_S3&#39;] = &#39;s3://metaflow&#39;<br>os.environ[&#39;METAFLOW_S3_VERIFY_SSL&#39;] = &#39;false&#39;<br>os.environ[&#39;METAFLOW_S3_ENDPOINT_URL&#39;] = &#39;http://1.2.3.4&#39;<br><br># Set environment variables for metaflow worker parallelism<br>os.environ[&#39;METAFLOW_RUN_MAX_WORKERS&#39;] = &#39;80&#39;<br><br># S3 variables<br>os.environ[&#39;AWS_DEFAULT_REGION&#39;] = &#39;us-east-1&#39;<br>#Pure Storage Flashblade endpoint with dataset<br>os.environ[&#39;S3_ENDPOINT_URL&#39;] = &#39;http://1.2.3.4&#39;<br>os.environ[&#39;AWS_ACCESS_KEY_ID&#39;] = &#39;PSFBSAZRDK****HIABGCMD&#39;<br>os.environ[&#39;AWS_SECRET_ACCESS_KEY&#39;] = &#39;4F4F10877****615BMCM&#39;<br><br>#define a class to hold all our steps<br>class S3ParallelCellFlow(FlowSpec):</pre><p>In this first code section I start by defining the Kubernetes config file to use when a given step is assigned the @kubernetes decorator and the namespace, in this case default. The next section defines the S3 variables for metaflow to access a shared S3 datastore for the tasks artefacts (logs, outputs,…). I then set the maximum metaflow run workers, this is simply the limit of the number of parallel tasks I can run, so it should be sized accordingly to your environments capabilities. In the last portion I provide the S3 account access and secret keys.</p><p>Then a class is used to tie all our steps together to a callable module.</p><h4>Step 1 — start</h4><pre>    @step<br>    def start(self):<br>        #set split / batch tasks<br>        self.split = 32<br>        <br>        self.next(self.list_objects)</pre><p>I always define a start step to store specific variables within the MetaFlow objects self keyword.</p><h4>Step 2 — List objects</h4><pre>    @kubernetes(image=&#39;jboothomas/metaflow-image:latest&#39;, memory=6000, cpu=4, disk=1024, secrets=[&#39;fb-secret&#39;])<br>    @step<br>    def list_objects(self):<br>        import boto3<br><br>        s3_client = boto3.client(<br>            &#39;s3&#39;,<br>            endpoint_url=os.environ[&#39;S3_ENDPOINT_URL&#39;],<br>            aws_access_key_id=os.environ[&#39;AWS_ACCESS_KEY_ID&#39;],<br>            aws_secret_access_key=os.environ[&#39;AWS_SECRET_ACCESS_KEY&#39;],<br>            verify=False<br>        )<br><br>        self.bucket_name = &#39;warp&#39;<br>        self.prefix = &#39;&#39;<br><br>        self.s3_objects = []<br>        paginator = s3_client.get_paginator(&#39;list_objects_v2&#39;)<br>        try:<br>            pages = paginator.paginate(Bucket=self.bucket_name, Prefix=self.prefix)<br>            for page in pages:<br>                if &quot;Contents&quot; in page:<br>                    for obj in page[&quot;Contents&quot;]:<br>                        self.s3_objects.append(obj[&quot;Key&quot;])<br>        except botocore.exceptions.ClientError as e:<br>            if e.response[&#39;Error&#39;][&#39;Code&#39;] == &#39;NoSuchBucket&#39;:<br>                raise ValueError(f&quot;Bucket &#39;{self.bucket_name}&#39; does not exist.&quot;)<br>            else:<br>                raise<br><br>   <br>        self.next(self.batch)</pre><p>The first line of this section calls the MetaFlow Kubernetes operator, for this we need to define an image, the memory, cpu and disk to be assigned to the deployed pod and any additional information. In my case I also provide a secret that contains the S3 access, secret keys and endpoint url to my FlashBlade S3 storage.</p><p>I used the following command to create such a secret:</p><pre>kubectl create secret generic fb-secret --from-literal=AWS_ACCESS_KEY_ID=PSF***CMD --from-literal=AWS_SECRET_ACCESS_KEY=4F4F****MCM --from-literal=S3_ENDPOINT_URL=http://1.2.3.4</pre><p>The next section of code defines a boto3 S3 client and the bucket to list the objects from. Using the self metaflow keyword variable I create a list to hold all the keys returned: self.s3_objects = []</p><p>Listing is a lengthy process as one has to iterate over pages of 1000 objects, if you are doing repetitive processing of a bucket that has no content change I would recommend storing this list and pulling it back in to save time.</p><h4>Step 3 — Split into batches</h4><pre>@step<br>    def batch(self):<br>        &quot;&quot;&quot;<br>        Splits the list into n batches.<br>        &quot;&quot;&quot;<br>        split = self.split<br>        batch_size = len(self.s3_objects) // split<br>        self.batches = [<br>            self.s3_objects[i * batch_size:(i + 1) * batch_size]<br>            for i in range(split)<br>        ]<br>        self.next(self.get_headers, foreach=&quot;batches&quot;)</pre><p>In the batch step I split the total objects returned by the list into a defined number of sub batches that are passed into the next step via the foreach. This will spin up n pods equal to the split count upto our maximum metaflow worker setting (global limit on flow parallelism).</p><h4>Step 4 —Per batch get headers</h4><pre>@kubernetes(image=&#39;jboothomas/metaflow-image:latest&#39;, memory=1000, cpu=1, disk=1024, secrets=[&#39;fb-secret&#39;])   <br>    @step<br>    def get_headers(self):<br>        import time<br>        import boto3<br><br>        geth_start_time = time.time()<br><br>        s3_client = boto3.client(<br>            &#39;s3&#39;,<br>            endpoint_url=os.environ[&#39;S3_ENDPOINT_URL&#39;],<br>            aws_access_key_id=os.environ[&#39;AWS_ACCESS_KEY_ID&#39;],<br>            aws_secret_access_key=os.environ[&#39;AWS_SECRET_ACCESS_KEY&#39;],<br>            verify=False<br>        )<br><br>        s3_batch_size = len(self.input)<br>        print(f&quot;this batch length: {s3_batch_size}&quot;)<br><br>        self.headers = []<br>        for key in self.input:<br>            try:<br>                response = s3_client.head_object(Bucket=self.bucket_name, Key=key)<br>                header_data = {  # Create a dictionary to store all relevant headers<br>                    &quot;key&quot;: key,<br>                    &quot;content_type&quot;: response.get(&#39;ContentType&#39;),<br>                    &quot;content_length&quot;: response.get(&#39;ContentLength&#39;), # Size in bytes<br>                    &quot;last_modified&quot;: response.get(&#39;LastModified&#39;), # Last modified timestamp<br>                    &quot;etag&quot;: response.get(&#39;ETag&#39;),<br>                    &quot;metadata&quot;: response.get(&#39;Metadata&#39;, {}), # User-defined metadata<br>                    &quot;accept_ranges&quot;: response.get(&#39;AcceptRanges&#39;),<br>                    &quot;cache_control&quot;: response.get(&#39;CacheControl&#39;),<br>                    &quot;content_disposition&quot;: response.get(&#39;ContentDisposition&#39;),<br>                    &quot;content_encoding&quot;: response.get(&#39;ContentEncoding&#39;),<br>                    &quot;expires&quot;: response.get(&#39;Expires&#39;),<br>                    &quot;server_side_encryption&quot;: response.get(&#39;ServerSideEncryption&#39;),<br>                    &quot;sse_customer_algorithm&quot;: response.get(&#39;SSECustomerAlgorithm&#39;),<br>                    &quot;sse_customer_key_md5&quot;: response.get(&#39;SSECustomerKeyMD5&#39;),<br>                    &quot;sse_kms_key_id&quot;: response.get(&#39;SSEKMSKeyId&#39;),<br>                    &quot;storage_class&quot;: response.get(&#39;StorageClass&#39;),<br>                    &quot;website_redirect_location&quot;: response.get(&#39;WebsiteRedirectLocation&#39;),<br>                    # Add other headers as needed<br>                }<br>                self.headers.append(header_data)            <br>            except botocore.exceptions.ClientError as e:<br>                print(f&quot;Error getting header for {key}: {e}&quot;)<br>                self.headers.append({&quot;key&quot;: key, &quot;error&quot;: str(e)})<br><br>        geth_end_time = time.time()<br>        elapsed_time = geth_end_time - geth_start_time<br>        headers_per_second = s3_batch_size / elapsed_time if elapsed_time &gt; 0 else 0<br><br>        print(f&quot;Processed {s3_batch_size} objects in {elapsed_time:.2f} seconds. Headers/sec: {headers_per_second:.2f}&quot;)<br><br>        self.batch_metrics = {&quot;headers_per_second&quot;: headers_per_second, &quot;batch_size&quot;: s3_batch_size, &quot;elapsed_time&quot;: elapsed_time, &#39;start_time&#39;: geth_start_time, &#39;end_time&#39;:geth_end_time}<br>        <br>        self.next(self.join_results)</pre><p>Each batch is spun up as a unique pod on the Kubernetes cluster. Each pod takes its given chunk of object keys and proceeds to pull the header information storing the results in a self.headers item.</p><p>When pre-processing our data you often need to base the following steps on given metadata that is stored within an objects header. This step gets us that information for any following steps where it may be needed.</p><h4>Step 5 — Collate results</h4><pre>@step<br>    def join_results(self, inputs): # The key is here<br>        <br>        self.all_headers = []<br>        self.all_metrics = []<br>        start_times = []<br>        end_times = []<br>        for input in inputs:<br>            self.all_headers.extend(input.headers)<br>            if hasattr(input,&quot;batch_metrics&quot;):<br>                self.all_metrics.append(input.batch_metrics)<br>                start_times.append(input.batch_metrics[&quot;start_time&quot;])<br>                end_times.append(input.batch_metrics[&quot;end_time&quot;])<br><br>        self.earliest_start_time = min(start_times) if start_times else None<br>        self.latest_end_time = max(end_times) if end_times else None<br><br>        self.next(self.end)</pre><p>At this point data processing steps could be applied either as more foreach batches or filtering the returned listings and processing. In this example I simply proceed to join the results and calculate the earliest start time and the latest end time to get a total elapsed for the overall get header operation.</p><h4>Step 7 — Output flow metrics</h4><pre>    @pypi(python=&#39;3.10.11&#39;, packages={&#39;boto3&#39;: &#39;1.34.112&#39;, &#39;pandas&#39; :&#39;2.2.3&#39;})<br>    @step<br>    def end(self):<br>        import time<br>        import pandas as pd<br>        import json<br>        <br>        df = pd.DataFrame(self.all_headers)<br>        print(df.head())<br><br>        metrics_df = pd.DataFrame(self.all_metrics)<br>        print(&quot;\nBatch Metrics Summary:&quot;)<br>        print(metrics_df)<br><br>        total_processed_objects = metrics_df[&#39;batch_size&#39;].sum()<br>        total_elapsed_time = self.latest_end_time - self.earliest_start_time if self.latest_end_time and self.earliest_start_time else 0<br><br>        overall_headers_per_second = total_processed_objects / total_elapsed_time if total_elapsed_time &gt; 0 else 0<br>        print(f&quot;\nOverall Headers per Second: {overall_headers_per_second:.2f}&quot;)<br>        print(f&quot;\nOverall time elapsed in Second: {total_elapsed_time:.2f}&quot;)<br><br>        ## additional code to show per object obtained information ##<br>        if self.all_headers: # Check if the list is not empty<br>            print(&quot;\nFirst 2 Header Elements:&quot;)<br>            for i, header in enumerate(self.all_headers[:2]): # Iterate only through the first 5<br>                print(f&quot;    {key}: {json.dumps(value, indent=4, default=str)}&quot;)<br>        else:<br>            print(&quot;\nNo headers were collected.&quot;)</pre><p>The end step outputs relevant metrics for the overall Metaflow operation, I am interested in the overall headers per second and total time spent listing the object headers so as to see how my parallelism impacts my processing speed.</p><h4>Step 8 — Run the flow</h4><pre>run = NBRunner(flow=S3ParallelCellFlow).nbrun()</pre><p>As I am running from within a jupyter notebook cell the above single line will execute the entire flow.</p><h3>Parallelism and S3 performance</h3><p>I ran the above code against a FlashBlade bucket with 1 million objects and varied the parallelism of the get_headers operation to see the impact this has on the overall performance.</p><p>In my case based on the available compute of the Kubernetes platform and the actual FlashBlade configuration, with 80 parallel workers I achieved 15&#39;804 get header operations per second !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dObdiuN1_UQwN5LBLZ4_PQ.png" /></figure><p>This would seem to be the upper bounds of my lab setup, more client compute and a bigger FlashBlade would push this result higher.</p><p>I proceeded to run the same code against an AWS Bucket with 1 million objects and compare with my FlashBlade results. If fast S3 performance is needed for your workloads, Pure Storage FlashBlade delivers!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z7WNfhnHyg8Asb0SWJusDA.png" /></figure><h3>Conclusion</h3><p>In this coming age of S3 powered AI workloads S3 metadata performance will be key in order to process in either pre or post workflow steps the data. FlashBlade was built around metadata performance and the ability to scale to adapt not only to usable raw storage space but also performance. Each blade within a FlashBlade cluster adds 600&#39;000 metadata IOPS, a single chassis can house 10 blades and multiple chassis can be stacked to create a platform that delivers true metadata performance at scale.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0708bda12cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RAG and the challenge of raw to embedded dataset size.]]></title>
            <link>https://jboothomas.medium.com/rag-and-the-challenge-of-raw-to-embedded-dataset-size-4dbe70722cd2?source=rss-3f68706e8d2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4dbe70722cd2</guid>
            <category><![CDATA[pure-storage]]></category>
            <category><![CDATA[milvus]]></category>
            <dc:creator><![CDATA[jboothomas]]></dc:creator>
            <pubDate>Mon, 22 Jul 2024 07:32:33 GMT</pubDate>
            <atom:updated>2024-07-22T07:32:33.779Z</atom:updated>
            <content:encoded><![CDATA[<p>With the increase of RAG enterprise deployments it is always interesting to see how things work under the covers. With that in mind in this “how to blog” I will go over the code to embed text chunks from files into a vector Database and look into the storage space required.</p><p>When leveraging a vector DB for a RAG use case we search across the embeddings based on the user query and return the most relevant hits. The associated text of these hits and the initial query is then passed on to the LLM for it to generate the response based on this enhanced context.</p><p>The vector database has to not only store the vector representation but also the raw text associated, so let’s get that setup and then see what impact a large amount of source data has on the storage required for the vectorDB.</p><h4>Setup</h4><p>I already have a milvus instance running within a kubernetes cluster using a Pure Storage Flashblade for the S3 backend. Milvus was installed using the milvus operator and the following values.yaml was applied during the deployment of the instance:</p><pre>apiVersion: milvus.io/v1beta1<br>kind: Milvus<br>metadata:<br>  name: jbt-milvus<br>  labels:<br>    app: milvus<br>spec:<br>  mode: cluster # Omit other fields ...<br>  config:<br>    minio:<br>      # your bucket name<br>      bucketName: jbt-milvus<br>      # Optional, config the prefix of the bucket milvus will use<br>      rootPath: milvus/jbt-milvus<br>      useSSL: false<br>  dependencies:<br>    storage:<br>      # enable external object storage<br>      external: true<br>      type: S3 # MinIO | S3<br>      # the endpoint of AWS S3<br>      endpoint: flashblade.purestorage.com<br>      #useSSL: false<br>      # the secret storing the access key and secret key<br>      secretRef: &quot;jbt-milvus-s3-secret&quot;</pre><p>For ease of use I also added a loadbalancer service so as to obtain from metalLB an IP visible from my workstation, here is the quick k8s config for that:</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: jbt-milvus-loadbalancer<br>spec:<br>  type: LoadBalancer<br>  selector:<br>    app.kubernetes.io/component: proxy<br>    app.kubernetes.io/instance: jbt-milvus<br>    app.kubernetes.io/name: milvus<br>    milvus.io/service: &quot;true&quot;<br>  ports:<br>    - protocol: TCP<br>      port: 19530<br>      targetPort: 19530</pre><p>The ‘jbt-milvus-s3-secret’ contains the relevant S3 access and secret keys for the S3 object account, here is the layout of the required yaml:</p><pre>apiVersion: v1<br>kind: Secret<br>metadata:<br>  name: jbt-milvus-s3-secret<br>type: Opaque<br>stringData:<br>  accesskey: PSFB*****BJEIA<br>  secretkey: A121*****eJOEN</pre><p>Applying the above yamls results in a running milvus instance accessible from outside the k8s cluster, and it should look similar to this:</p><pre>NAME                                             READY   STATUS    RESTARTS      AGE   IP               NODE       NOMINATED NODE   READINESS GATES<br>jbt-milvus-etcd-0                                1/1     Running   0             43h   172.168.96.110   jbt-54-k   &lt;none&gt;           &lt;none&gt;<br>jbt-milvus-etcd-1                                1/1     Running   0             45h   172.168.96.151   jbt-51-k   &lt;none&gt;           &lt;none&gt;<br>jbt-milvus-etcd-2                                1/1     Running   0             13d   172.168.96.163   jbt-51-k   &lt;none&gt;           &lt;none&gt;<br>jbt-milvus-milvus-datacoord-764f9475c5-7kjcb     1/1     Running   0             18h   172.168.96.226   jbt-52-k   &lt;none&gt;           &lt;none&gt;<br>jbt-milvus-milvus-datanode-7f899c8c58-7mj5f      1/1     Running   0             18h   172.168.96.241   jbt-52-k   &lt;none&gt;           &lt;none&gt;<br>jbt-milvus-milvus-indexcoord-5b5f8655f-b5qcw     1/1     Running   0             18h   172.168.96.109   jbt-54-k   &lt;none&gt;           &lt;none&gt;<br>jbt-milvus-milvus-indexnode-8d86c6db8-2c5mt      1/1     Running   0             18h   172.168.96.216   jbt-52-k   &lt;none&gt;           &lt;none&gt;<br>jbt-milvus-milvus-proxy-5dcccff4b-chngq          1/1     Running   0             18h   172.168.96.233   jbt-52-k   &lt;none&gt;           &lt;none&gt;<br>jbt-milvus-milvus-querycoord-fff7966b7-gm89l     1/1     Running   1 (38h ago)   38h   172.168.96.189   jbt-51-k   &lt;none&gt;           &lt;none&gt;<br>jbt-milvus-milvus-querynode-0-54f76d6f6f-8cw2g   1/1     Running   0             17h   172.168.96.113   jbt-54-k   &lt;none&gt;           &lt;none&gt;<br>jbt-milvus-milvus-rootcoord-99477cd9f-zm7cp      1/1     Running   0             18h   172.168.96.229   jbt-52-k   &lt;none&gt;           &lt;none&gt;<br>jbt-milvus-pulsar-bookie-0                       1/1     Running   0             28d   172.168.96.49    jbt-53-k   &lt;none&gt;           &lt;none&gt;<br>jbt-milvus-pulsar-bookie-1                       1/1     Running   0             28d   172.168.96.95    jbt-54-k   &lt;none&gt;           &lt;none&gt;<br>jbt-milvus-pulsar-bookie-2                       1/1     Running   0             45h   172.168.96.165   jbt-51-k   &lt;none&gt;           &lt;none&gt;<br>jbt-milvus-pulsar-broker-0                       1/1     Running   0             13d   172.168.96.142   jbt-51-k   &lt;none&gt;           &lt;none&gt;<br>jbt-milvus-pulsar-proxy-0                        1/1     Running   0             23h   172.168.96.230   jbt-52-k   &lt;none&gt;           &lt;none&gt;<br>jbt-milvus-pulsar-recovery-0                     1/1     Running   0             45h   172.168.96.172   jbt-51-k   &lt;none&gt;           &lt;none&gt;<br>jbt-milvus-pulsar-zookeeper-0                    1/1     Running   0             44h   172.168.96.156   jbt-51-k   &lt;none&gt;           &lt;none&gt;<br>jbt-milvus-pulsar-zookeeper-1                    1/1     Running   0             45h   172.168.96.160   jbt-51-k   &lt;none&gt;           &lt;none&gt;<br>jbt-milvus-pulsar-zookeeper-2                    1/1     Running   0             28d   172.168.96.111   jbt-54-k   &lt;none&gt;           &lt;none&gt;</pre><p>Within a Jupyter notebook I load a kernel with the following requirements installed: pymilvus 2.4.3, PyPDF2 3.0.1, torch 2.3.0 and transformers 4.41.2.</p><h4>Code</h4><p>The first step is to load the required modules our tokenizer and model:</p><pre>import os<br>import torch<br><br>from pymilvus import connections, Collection, CollectionSchema, DataType, FieldSchema, utility<br>from PyPDF2 import PdfReader<br>from transformers import DPRContextEncoder, DPRQuestionEncoderTokenizer<br><br>tokenizer = DPRQuestionEncoderTokenizer.from_pretrained(&quot;facebook/dpr-ctx_encoder-single-nq-base&quot;)<br>model = DPRContextEncoder.from_pretrained(&quot;facebook/dpr-ctx_encoder-single-nq-base&quot;)</pre><p>Then I define the following functions, the connection to our milvus database:</p><pre>def connect_to_milvus():<br>    connections.connect(alias=&quot;default&quot;, host=&quot;1.2.3.4&quot;, port=&quot;19530&quot;)<br>    print(&quot;Connected to Milvus.&quot;)</pre><p>The creation of a milvus collection and a function to insert our data. Here I define the schema with id, embeddings and text for my fields:</p><pre>def create_collection(collection_name, dim=768):<br>    exists = utility.has_collection(collection_name)<br><br>    if not exists:<br>        print(f&quot;Collection {collection_name} does not exist.&quot;)<br>        fields = [<br>            FieldSchema(name=&quot;id&quot;, dtype=DataType.INT64, is_primary=True, auto_id=True),<br>            FieldSchema(name=&quot;embeddings&quot;, dtype=DataType.FLOAT_VECTOR, dim=dim),<br>            FieldSchema(name=&quot;text&quot;, dtype=DataType.VARCHAR, max_length=512)                    <br>        ]<br>        schema = CollectionSchema(fields, description=&quot;Embedding Collection&quot;)<br>        collection = Collection(name=collection_name, schema=schema)<br>        print(f&quot;Collection {collection_name} created.&quot;)<br>    else:<br>        collection = Collection(name=collection_name)<br>        print(f&quot;Collection {collection_name} already exists.&quot;)<br>    return collection</pre><pre>def insert_embeddings(collection, embeddings, texts):<br>    data = [embeddings, texts]<br>    ids = collection.insert(data)<br>    collection.flush()<br>    return ids</pre><p>Then functions to extract text from a files in a folder, chunk and encode the text. <em>Note: if you have suggestions around how best to handle chunk length and byte size of the actual schema do say</em>:</p><pre>def extract_text_from_pdf(pdf_path):<br>    # Implement PDF reading here<br>    # Example: Using PyPDF2 (pip install PyPDF2)<br>    reader = PdfReader(pdf_path)<br>    text = &#39;&#39;<br>    for page in reader.pages:<br>        text += page.extract_text()<br>    return text</pre><pre>def chunk_text(text, chunk_size=512):<br>    words = text.split()<br>    chunks = []<br>    current_chunk = []<br>    current_length = 0<br>    <br>    for word in words:<br>        # Calculate the byte length if the word is added<br>        additional_length = len(word.encode(&#39;utf-8&#39;)) + (1 if current_chunk else 0)<br>        new_length = current_length + additional_length<br>        if additional_length &lt;= chunk_size:<br>            current_chunk.append(word)<br>            current_length = new_length<br>        else:<br>            chunks.append(&#39; &#39;.join(current_chunk))<br>            current_chunk = [word]<br>            current_length = len(word.encode(&#39;utf-8&#39;))<br><br>    # Add the last chunk if it exists<br>    if current_chunk:<br>        chunks.append(&#39; &#39;.join(current_chunk))<br><br>    return chunks</pre><pre>def encode_text(text):<br>    inputs = tokenizer(text, return_tensors=&quot;pt&quot;, truncation=True, max_length=512)<br>    outputs = model(**inputs)<br>    return outputs.pooler_output.detach().numpy()[0] #assuming single embedding</pre><pre>def move_file_to_done(file_name, source_folder, destination_folder):<br>    # Construct full file paths<br>    source_path = os.path.join(source_folder, file_name)<br>    destination_path = os.path.join(destination_folder, file_name)<br><br>    # Move the file<br>    try:<br>        shutil.move(source_path, destination_path)<br>        print(f&#39;File {file_name} moved to {destination_folder}&#39;)<br>    except FileNotFoundError:<br>        print(f&#39;File {file_name} not found in {source_folder}&#39;)<br>    except Exception as e:<br>        print(f&#39;Error moving file: {e}&#39;)</pre><p>and finally a function to process the files in a folder:</p><pre>def process_files(in_directory, out_directory, collection):<br>    for filename in os.listdir(in_directory):<br>        if filename.endswith(&#39;.pdf&#39;):<br>            print(f&quot;Processing {filename}.&quot;)<br>            texts = []<br>            embeddings = []<br>            pdf_path = os.path.join(in_directory, filename)<br>            text = extract_text_from_pdf(pdf_path)<br>            text_chunks = chunk_text(text)    <br>        <br>            for txt_chunk in text_chunks:<br>                embedding = encode_text(txt_chunk)<br>                texts.append(txt_chunk)<br>                embeddings.append(embedding)<br>        <br>            ids = insert_embeddings(collection, embeddings, texts)<br>            move_file_to_done(filename, in_directory, out_directory)<br>            print(f&quot;Inserted {ids.insert_count} embeddings from {filename}.&quot;)<br>        <br>        elif filename.endswith(&#39;.txt&#39;):<br>            print(f&quot;Processing {filename}.&quot;)<br>            texts = []<br>            embeddings = []<br>            txt_path = os.path.join(in_directory, filename)<br>            text = extract_text_from_txt(txt_path)<br>            text_chunks = chunk_text(text)    <br><br>            for txt_chunk in text_chunks:<br>                embedding = encode_text(txt_chunk)<br>                texts.append(txt_chunk)<br>                embeddings.append(embedding)<br><br>            ids = insert_embeddings(collection, embeddings, texts)<br>            move_file_to_done(filename, in_directory, out_directory)<br>            print(f&quot;Inserted {ids.insert_count} embeddings from {filename}.&quot;)</pre><h4>Embedding a single PDF</h4><p>I connect and create a collection to store my embeddings by running the following code:</p><pre>connect_to_milvus()<br>collection_name = &quot;my_test_rag&quot;<br>dimension_size = 768<br>collection = create_collection(collection_name, dimension_size)</pre><p>This will return:</p><pre>Connected to Milvus.<br>Collection my_test_rag does not exist.<br>Collection my_test_rag created.</pre><p>Then I run the processing of the files within a given directory :</p><pre>my_source_directory = &#39;./PDFs&#39;<br>my_dest_directory = &#39;./donePDFs&#39;<br> <br>process_files(my_source_directory, my_dest_directory, collection)<br></pre><p>Running against a single PDF file inserted 1523 embeddings.</p><h4>Searching the vector database</h4><p>I can now query the vector database and retrieve relevant text chunks:</p><pre>from pymilvus import connections, Collection, utility<br>from transformers import DPRQuestionEncoderTokenizer, DPRQuestionEncoder<br><br>tokenizer = DPRQuestionEncoderTokenizer.from_pretrained(&quot;facebook/dpr-question_encoder-single-nq-base&quot;)<br>model = DPRQuestionEncoder.from_pretrained(&quot;facebook/dpr-question_encoder-single-nq-base&quot;)<br><br><br>collection = Collection(name=&quot;my_test_rag&quot;)<br># Check if the index already exists, and create if it does not<br>if not collection.has_index():<br>    index_params = {<br>        &quot;index_type&quot;: &quot;IVF_FLAT&quot;,<br>        &quot;params&quot;: {&quot;nlist&quot;: 100},<br>        &quot;metric_type&quot;: &quot;L2&quot;<br>    }<br>    collection.create_index(field_name=&quot;embeddings&quot;, index_params=index_params)<br><br># Load the collection into memory<br>collection.load()</pre><pre># Prepare a query text and encode it into a vector<br>query_text = &quot;Flashblade S3 statistics&quot;<br>inputs = tokenizer(query_text, return_tensors=&quot;pt&quot;)<br>query_embedding = model(**inputs).pooler_output.detach().numpy()<br><br># Convert the embedding to a list of floats<br>query_embedding = query_embedding.tolist()<br><br># Perform the search<br>search_params = {&quot;metric_type&quot;: &quot;L2&quot;, &quot;params&quot;: {&quot;nprobe&quot;: 10}}<br>results = collection.search(<br>    data=query_embedding, <br>    anns_field=&quot;embeddings&quot;, <br>    param=search_params, <br>    limit=5, <br>    expr=None,<br>    output_fields=[&quot;text&quot;]<br>)<br># Print the search results<br>for result in results:<br>    for hit in result:<br>        print(f&quot;ID: {hit.id}, Score: {hit.distance}, Text: {hit.entity.get(&#39;text&#39;)}&quot;)</pre><p>Will retrieve the matching text chunks, for example:</p><pre>ID: 450165976472778458, Score: 95.83973693847656, <br>Text: Hover over any part of a chart to display values for a specific point <br>in time. The values that appear in the point-in-time tooltips are rounded to<br> two decimal places. The Performance Chart The following example displays <br>the IOPS statistics on the array at precisely 5:00:00 on March 12 . The <br>Performance panel includes the Latency, IOPS, and Bandwidth charts. Latency<br> The Latency chart displays the average latency times for various operations.<br> •Read Latency (R)<br>...</pre><h4>Embedding thousands of documents</h4><p>So what happens when I build a collection based on several GBs of text files?</p><p>For this I downloaded 19101 text files from the Gutenberg project for a total raw volume of 7.1GB. Using the above code this dataset was ingested into the vector database resulting in just over 14 million embeddings. The final count of entities in the collection is obtained using:</p><pre>from pymilvus import connections, Collection, utility<br># Connect to Milvus<br>connections.connect(&quot;default&quot;, host=&quot;1.2.3.4&quot;, port=&quot;19530&quot;)<br><br>collection_name = &quot;my_test_rag&quot;<br>collection = Collection(name=collection_name)<br># Get the number of entities in the collection<br>num_entities = collection.num_entities<br>print(f&quot;The number of entities in the collection &#39;{collection_name}&#39; is: {num_entities}&quot;)</pre><p>Result:</p><pre>The number of entities in the collection &#39;my_test_rag&#39; is: 14379441</pre><p>Now Milvus creates index_files, insert_log &amp; stats_log objects. I waited for all the insert_logs to be played into the index_files and for compaction and deep gc to run on the Milvus platform so as to get the final storage size for the database. To obtain the total storage space used for my collection I list and summarise the objects created on the S3 storage layer:</p><pre>aws s3 --endpoint-url=http://192.168.40.165 --profile fbstaines03 ls --summarize --human-readable --recursive s3://jbt-milvus/milvus/jbt-milvus/index_files | grep Total<br>Total Objects: 4362<br>   Total Size: 61.0 GiB<br><br>aws s3 --endpoint-url=http://192.168.40.165 --profile fbstaines03 ls --summarize --human-readable --recursive s3://jbt-milvus/milvus/jbt-milvus/insert_log | grep Total<br>Total Objects: 4030<br>   Total Size: 45.2 GiB</pre><p>We have experienced a 8x (or 15x if we consider all db log files) increase in storage required from our initial raw text dataset to its vectored and chunked database version.</p><p>Another notable aspect is the fact that during ingest the database size grows to several times the end result! This is due to the ingest of data into the insert_log(s) these are then played into index_logs with compression, compaction and garbage collection helping to reduce the storage space required by the database. During the above test my database grew to several hundred<strong> </strong>GiB, multiple times the actual end total size. As per the following screen shot where I took measurements of the evolution of the backend S3 storage usage over several hours:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*wFdyIF152PlW4iamAk2jFA.png" /><figcaption>Example fluctuation of Milvus S3 storage space used</figcaption></figure><h4>Conclusion</h4><p>The workload of an enterprise vector database implies:</p><ul><li>increased storage footprint from raw data to vectors in the database</li><li>fluctuating size during ingest of the vector database</li><li>frequent ingest to maintain searchable up to date domain knowledge</li></ul><p>A <a href="https://www.purestorage.com/products/unstructured-data-storage/flashblade-s.html">storage platform</a> built around simplicity, consistent performance and scalability is key when considering one&#39;s enterprise RAG use case, we tend to forget that not everything is about the GPU !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4dbe70722cd2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL query S3 objects with Apache drill]]></title>
            <link>https://jboothomas.medium.com/sql-query-s3-objects-with-apache-drill-5cc24f35f49e?source=rss-3f68706e8d2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cc24f35f49e</guid>
            <category><![CDATA[flashblade]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[apache-drill]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[parquet]]></category>
            <dc:creator><![CDATA[jboothomas]]></dc:creator>
            <pubDate>Fri, 10 May 2024 12:53:03 GMT</pubDate>
            <atom:updated>2024-05-10T12:53:03.500Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article I will cover how to setup and configure apache drill to run SQL queries against parquet files stored in an S3 bucket.</p><p>For this setup I will be using an ubuntu 20.04 virtual machine and a Pure Storage FlashBlade S//200 for S3 storage.</p><p>I start by updating and installing the requirements and apache base package:</p><pre>apt update<br>apt install openjdk-8-jdk<br>wget https://dlcdn.apache.org/drill/1.21.1/apache-drill-1.21.1.tar.gz<br>tar -xvf apache-drill-1.21.1.tar.gz<br>cd apache-drill-1.21.1<br><br>~/apache-drill-1.21.1$ ls<br>KEYS  LICENSE  NOTICE  README.md  bin  conf  git.properties  jars  sample-data  winutils</pre><p>To access S3, I will configure the S3 storage plugin in Apache Drill, to do so start apache-drill bin/drill-embedded then from a browser navigate to the web service <a href="http://your_ip:8047:">http://your_ip:8047:</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*53KSRvug9Igpi5ggY-tP_A.png" /></figure><p>Select create and paste in the following json amended to suit your environment:</p><pre>{<br>  &quot;type&quot;: &quot;file&quot;,<br>  &quot;connection&quot;: &quot;s3a://nyctaxi&quot;,<br>  &quot;config&quot;: {<br>    &quot;fs.s3a.endpoint&quot;: &quot;&lt;your_s3_endpoint&gt;&quot;,<br>    &quot;fs.s3a.connection.ssl.enabled&quot;: false,<br>    &quot;fs.s3a.access.key&quot;: &quot;&lt;your_s3_accesskey&gt;&quot;,<br>    &quot;fs.s3a.secret.key&quot;: &quot;&lt;your_s3_secretkey&gt;&quot;<br>  },<br>  &quot;workspaces&quot;: {<br>    &quot;root&quot;: {<br>      &quot;location&quot;: &quot;/&quot;,<br>      &quot;writable&quot;: false,<br>      &quot;defaultInputFormat&quot;: null,<br>      &quot;allowAccessOutsideWorkspace&quot;: false<br>    }<br>  },<br>  &quot;formats&quot;: {<br>    &quot;parquet&quot;: {<br>      &quot;type&quot;: &quot;parquet&quot;<br>    }<br>  },<br>  &quot;authMode&quot;: &quot;SHARED_USER&quot;,<br>  &quot;enabled&quot;: true<br>}</pre><p>With that applied you should see the new storage plugin listed alongside the defaults:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D_yGoJGEAL3X6nwig5RWkw.png" /></figure><p>Listing all databases visible from apache drill, now shows our newly defined s3 storage plugin:</p><pre>apache drill&gt; show databases;<br>+--------------------------------+<br>|          SCHEMA_NAME           |<br>+--------------------------------+<br>| dfs.default                    |<br>| dfs.root                       |<br>| dfs.tmp                        |<br>| information_schema             |<br>| sys                            |<br>| cp.default                     |<br>| nyctaxis3parquetbucket.default |<br>| nyctaxis3parquetbucket.root    |<br>+--------------------------------+<br>8 rows selected (0.184 seconds)</pre><p>Leveraging this and a known parquet file on the s3 backend I can run some basic queries:</p><pre>apache drill (nyctaxis3parquetbucket)&gt; select COUNT(*) FROM `s3a://nyctaxi/yellow_tripdata_2022-01.parquet` WHERE trip_distance &gt; 100;<br>+--------+<br>| EXPR$0 |<br>+--------+<br>| 135    |<br>+--------+<br>1 row selected (0.289 seconds)<br><br>apache drill (nyctaxis3parquetbucket)&gt; select COUNT(*) FROM `s3a://nyctaxi/yellow_tripdata_2022-01.parquet` WHERE trip_distance &lt; 100;<br>+---------+<br>| EXPR$0  |<br>+---------+<br>| 2463796 |<br>+---------+<br>1 row selected (0.319 seconds)</pre><p>It is also possible to wildcard the parquet files that make up the dataset to issue the query across all matching files `yellow_tripdata_2022-??.parquet`:</p><pre>apache drill (nyctaxis3parquetbucket)&gt; select COUNT(*) FROM `s3a://nyctaxi/yellow_tripdata_2022-??.parquet` WHERE trip_distance &gt; 100;<br>+--------+<br>| EXPR$0 |<br>+--------+<br>| 1529   |<br>+--------+<br>1 row selected (0.782 seconds)<br>apache drill (nyctaxis3parquetbucket)&gt; select COUNT(*) FROM `s3a://nyctaxi/yellow_tripdata_2022-??.parquet` WHERE trip_distance &lt; 100;<br>+----------+<br>|  EXPR$0  |<br>+----------+<br>| 39654569 |<br>+----------+<br>1 row selected (1.039 seconds)</pre><p>On the Pure Storage Flashblade S//200 we can see the S3 IO from the query:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*_Q_buJy6Drzydmgpc-sSCA.png" /></figure><p>As well as the specific S3 protocol operation latencies:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*Sq4ErFwpu7XezD_bOcie8A.png" /></figure><p>Apache drill and Pure Storage FlashBlade are yet another means to run SQL queries across S3 parquet objects stored on S3 effortless.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cc24f35f49e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lakefs.io on kubernetes with PureStorage FlashBlade]]></title>
            <link>https://jboothomas.medium.com/lakefs-io-on-kubernetes-with-purestorage-flashblade-9e0fe7c574a9?source=rss-3f68706e8d2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e0fe7c574a9</guid>
            <category><![CDATA[lakefs]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[flashblade]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[s3]]></category>
            <dc:creator><![CDATA[jboothomas]]></dc:creator>
            <pubDate>Fri, 01 Mar 2024 09:46:38 GMT</pubDate>
            <atom:updated>2024-03-01T09:46:38.826Z</atom:updated>
            <content:encoded><![CDATA[<p>As per their website L<strong>akeFS brings software engineering best practices and applies them to data engineering. </strong>Let’s go over how to get up and running with lakefs on kubernetes and Pure Storage Flashblade.</p><p>All of the following steps are done on a kubernetes cluster in the lakefs namespace.</p><h4>Deploying the database</h4><p>As per the lakefs requirements we first need a database to synchronize actions on your repositories.</p><p>For our postgres statefulset we need a secret for the database password:</p><pre>echo -n &#39;your_password_here&#39; | base64<br>eW91cl9wYXNzd29yZF9oZXJl</pre><p>Our postgres is defined as per the following yaml file, change your storageClassName to suit your environment.</p><pre>apiVersion: v1<br>kind: Secret<br>metadata:<br>  name: postgres-secret<br>type: Opaque<br>data:<br>  postgres-password: eW91cl9wYXNzd29yZF9oZXJl<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: postgres<br>spec:<br>  ports:<br>  - port: 5432<br>  clusterIP: None<br>  selector:<br>    app: postgres<br>---<br>apiVersion: apps/v1<br>kind: StatefulSet<br>metadata:<br>  name: postgres<br>spec:<br>  selector:<br>    matchLabels:<br>      app: postgres<br>  serviceName: &quot;postgres&quot;<br>  replicas: 1<br>  template:<br>    metadata:<br>      labels:<br>        app: postgres<br>    spec:<br>      containers:<br>      - name: postgres<br>        image: postgres:latest<br>        env:<br>        - name: POSTGRES_DB<br>          value: &quot;lakefsdb&quot;<br>        - name: POSTGRES_USER<br>          value: &quot;exampleuser&quot;<br>        - name: POSTGRES_PASSWORD<br>          valueFrom:<br>            secretKeyRef:<br>              name: postgres-secret<br>              key: postgres-password<br>        ports:<br>        - containerPort: 5432<br>        volumeMounts:<br>        - name: postgres-storage<br>          mountPath: /var/lib/postgresql/data<br>  volumeClaimTemplates:<br>  - metadata:<br>      name: postgres-storage<br>    spec:<br>      storageClassName: &quot;pwxdb-storage-class&quot;<br>      accessModes: [ &quot;ReadWriteOnce&quot; ]<br>      resources:<br>        requests:<br>          storage: 1Gi</pre><p>and deployed simply via:</p><pre>kubectl -n lakefs apply -f postrgres.yaml</pre><p>Upon completion you should have a running postgres server within the desired namespace on the kubernetes cluster:</p><pre>kubectl -n lakefs get all<br>NAME             READY   STATUS              RESTARTS   AGE<br>pod/postgres-0   1/1     Running             0          8s<br><br>NAME               TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)    AGE<br>service/postgres   ClusterIP   None         &lt;none&gt;        5432/TCP   57s<br><br>NAME                        READY   AGE<br>statefulset.apps/postgres   1/1     8s</pre><h4>Deploying LakeFS</h4><p>To deploy lakefs we will be using the helm method and for this we need to provide certain values for the chart. These are specific to the storage platform and postgres database used so change to suit. In our case I have provided values for a Pure Storage FlashBlade as it delivers native S3 capabilities as required by LakeFS.</p><p>FlashBlade S3 is NOT built on top of a filesystem, as is the case with many other “s3 storage systems” with all the hidden limitations that this incurs (see versioning and object lock issues when running S3 backed by a file system).</p><p>The helm chart values:</p><pre>secrets:<br>    # replace this with the connection string of the database you created in a previous step:<br>    databaseConnectionString: postgres://exampleuser:your_password_here@postgres:5432/lakefsdb<br>    # replace this with a randomly-generated string<br>    authEncryptSecretKey: my_randomly_generated_string<br>lakefsConfig: |<br>    database:<br>      type: postgres<br>    blockstore:<br>      type: s3<br>      s3:<br>        force_path_style: true<br>        endpoint: http://192.168.4.104<br>        discover_bucket_region: false<br>        credentials:<br>          access_key_id: PSFBSA*****************GCBJEIA<br>          secret_access_key: A1211269*****************91c63eJOEN</pre><p>Then install using helm cli:</p><pre>helm install fb-lakefs lakefs/lakefs -n lakefs -f lakefs_helm_values.yml <br>NAME: fb-lakefs<br>LAST DEPLOYED: Fri Mar  1 08:42:43 2024<br>NAMESPACE: lakefs<br>STATUS: deployed<br>REVISION: 1<br>TEST SUITE: None<br>NOTES:<br>Thank you for installing lakeFS!<br><br>1. Run the following to get a url to start setting up lakeFS:<br>  export POD_NAME=$(kubectl get pods --namespace lakefs -l &quot;app.kubernetes.io/instance=fb-lakefs&quot; -o jsonpath=&quot;{.items[0].metadata.name}&quot;)<br>  kubectl wait --for=condition=ready pod $POD_NAME<br>  echo &quot;Visit http://127.0.0.1:8000/setup to use your application&quot;<br>  kubectl port-forward $POD_NAME 8000:8000 --namespace lakefs<br><br>2. See the docs on how to create your first repository: https://docs.lakefs.io/quickstart/repository.html</pre><p>I edit the services from ClusterIPs to NodePorts, to have a simple means of accessing the GUIs in a lab environment from outside the k8s cluster.</p><h4>Repositories, data import and visibility</h4><p>After connecting to the lakefs interface and creating the initial admin user we are presented with our main page where we can create a repository:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zjUXIRg6etGRAk6xDnPTCA.png" /></figure><p>Using the import functionality I will point my lakefs at a bucket containing some of the New York City taxi dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QKtx23a_x1DRdEJpkhV13w.png" /></figure><p>You should get a ‘success’ message upon completion of the import task:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2DoIBUAb2B0Z9QV333mf7A.png" /></figure><p>Within our repository we can browse and check the imported objects:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*smmRJg7WidxNMlARDJaBAw.png" /></figure><p>We can also run some queries against them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MXwirAk2kBCTvePDOp0I5w.png" /></figure><p>and of course all this while maintaining the familiar git mindest of commits, branches, tags and repositories:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sv_Dgt1zxR8ux69seRjWVg.png" /></figure><h4>Conclusion</h4><p>Lakefs provides data management as code using git-like operations, and when combined with the speed and simplicity at scale of Pure Storage FlashBlade it empowers the most critical aspect of an AI or analytics pipeline: the management of the datasets.</p><p>Further reading:</p><ul><li><a href="https://www.purestorage.com/products/unstructured-data-storage/flashblade-s.html">Pure Storage FlashBlade</a></li><li><a href="https://lakefs.io/">LakeFS</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e0fe7c574a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clickhouse and Flashblade S3]]></title>
            <link>https://jboothomas.medium.com/clickhouse-and-flashblade-s3-dd1bb2e241e5?source=rss-3f68706e8d2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd1bb2e241e5</guid>
            <category><![CDATA[flashblade]]></category>
            <category><![CDATA[clickhouse]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[s3-bucket]]></category>
            <dc:creator><![CDATA[jboothomas]]></dc:creator>
            <pubDate>Tue, 22 Aug 2023 07:53:14 GMT</pubDate>
            <atom:updated>2023-08-22T08:25:26.752Z</atom:updated>
            <content:encoded><![CDATA[<p>In this quick how to I will cover the steps to leverage Pure Storage Flashblade S3 storage with a Clickhouse installation.</p><h3>Disable SSL certificate validation</h3><p>In the lab environment I do not have SSL certificates in place in order to disable ssl verification the following line must be set within the /etc/clickhouse-server/config.wml file:</p><pre>&lt;openSSL&gt;<br>...<br>   &lt;client&gt;<br>     ...<br>     &lt;verificationMode&gt;none&lt;/verificationMode&gt;<br>     ...<br>   &lt;/client&gt;<br>&lt;/openSSL&gt;<br></pre><h3>External datasets</h3><p>After restarting the clickhouse-server service I connect using the clickhouse-client, and can run direct queries on datasets residing on my S3 storage:</p><pre>:) SELECT count() AS count<br>FROM s3(&#39;https://192.168.2.2/nyctaxi/*.parquet&#39;, &#39;PSF....EIA&#39;, &#39;A12....OEN&#39;);<br><br>Query id: f4d3e05f-5bc9-461a-806f-be675d4b60ec<br><br>┌────count─┐<br>│ 39656098 │<br>└──────────┘</pre><p>In the above example I provide the endpoint path to the bucket and dataset files, the s3_access_key and then the s3_secret_key.</p><h3>Clickhouse disks</h3><p>In order to leverage Flashblade S3 storage as a disk within Clickhouse I create a configuration file under /etc/clickhouse-server/conf.d/fb03.xml with the following contents:</p><pre>&lt;yandex&gt;<br>    &lt;storage_configuration&gt;<br>        &lt;disks&gt;<br>            &lt;fb03&gt;<br>                &lt;type&gt;s3&lt;/type&gt;<br>                &lt;endpoint&gt;https://192.168.2.2/clickhouse//&lt;/endpoint&gt;<br>                &lt;access_key_id&gt;PSFB....JEIA&lt;/access_key_id&gt;<br>                &lt;secret_access_key&gt;A1211....JOEN&lt;/secret_access_key&gt;<br>                &lt;region&gt;&lt;/region&gt;<br>                &lt;use_path_style_addressing&gt;true&lt;/use_path_style_addressing&gt;<br>            &lt;/fb03&gt;<br>            &lt;s3_cache&gt;<br>                &lt;type&gt;cache&lt;/type&gt;<br>                &lt;disk&gt;fb03&lt;/disk&gt;<br>                &lt;path&gt;/var/lib/clickhouse/disks/s3_cache/&lt;/path&gt;<br>                &lt;max_size&gt;10Gi&lt;/max_size&gt;<br>            &lt;/s3_cache&gt;<br>        &lt;/disks&gt;<br>        &lt;policies&gt;<br>            &lt;external&gt;<br>                &lt;volumes&gt;<br>                    &lt;s3&gt;<br>                        &lt;disk&gt;fb03&lt;/disk&gt;<br>                    &lt;/s3&gt;<br>                &lt;/volumes&gt;<br>            &lt;/external&gt;<br>        &lt;/policies&gt;<br>    &lt;/storage_configuration&gt;<br>&lt;/yandex&gt;</pre><p>I restart the clickhouse-server service and connect to the client, I then validate that the S3 storage disk is available within the Clickhouse environment:</p><pre>:) SELECT * FROM system.disks;<br><br>SELECT *<br>FROM system.disks<br><br>Query id: a18918e0-5755-4556-973e-dcceca69b354<br><br>┌─name────┬─path────────────────────────────┬───────────free_space─┬──────────total_space─┬─────unreserved_space─┬─keep_free_space─┬─type──┬─is_encrypted─┬─is_read_only─┬─is_write_once─┬─is_remote─┬─is_broken─┬─cache_path─┐<br>│ default │ /var/lib/clickhouse/            │           9573216256 │          48420556800 │           9573216256 │               0 │ local │            0 │            0 │             0 │         0 │         0 │            │<br>│ fb03    │ /var/lib/clickhouse/disks/fb03/ │ 18446744073709551615 │ 18446744073709551615 │ 18446744073709551615 │               0 │ s3    │            0 │            0 │             0 │         1 │         0 │            │<br>└─────────┴─────────────────────────────────┴──────────────────────┴──────────────────────┴──────────────────────┴─────────────────┴───────┴──────────────┴──────────────┴───────────────┴───────────┴───────────┴────────────┘<br><br>2 rows in set. Elapsed: 0.001 sec. </pre><p>With this configured I can create a table on the Flashblade S3 storage as follows:</p><pre>CREATE TABLE my_first_table<br>(<br>    `user_id` UInt32,<br>    `message` String,<br>    `timestamp` DateTime,<br>    `metric` Float32<br>)<br>ENGINE = MergeTree<br>PRIMARY KEY (user_id, timestamp)<br>SETTINGS storage_policy = &#39;external&#39;</pre><p>In the above SQL query the last line defines the storage policy to use for the table creation, in my case I named my policy “external” for the Flashblade S3 disk.</p><p>After creating this simple table I check the S3 buckets contents:</p><pre>$ aws s3api list-objects-v2  --profile fbstaines03 --no-verify-ssl --endpoint-url=https://192.168.2.2 --bucket clickhouse | grep Key<br>            &quot;Key&quot;: &quot;clickhouse_remove_objects_capability_752e5429-bcba-452c-bcda-b6214d76ddf0&quot;, <br>            &quot;Key&quot;: &quot;san/szimkjmkmjeidpvemqduhzbjidlst&quot;,            <br>            &quot;Key&quot;: &quot;ujj/gwjmmjasuhodjiliwmxvzkbwzozxn&quot;, </pre><p>I ran a quick tetst and created a second table and a new object was created on the Flashblade bucket “<strong>Key</strong>”: “gat/ywggwlxvdvwivllvqrljdkdkekeag”.</p><h3>Conclusion</h3><p>Clickhouse combined with Flashblade’ speed and simplicity at scale offers a powerful platform to extract value from your growing datasets while keeping things simple. To learn more about Pure Storage Flashblade, the only platform to provide consistent time to result at scale, <a href="https://www.purestorage.com/products/unstructured-data-storage/flashblade-s.html">click here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd1bb2e241e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Trino S3 via hive-metastore integration]]></title>
            <link>https://jboothomas.medium.com/trino-s3-via-hive-metastore-integration-9d4910c072b5?source=rss-3f68706e8d2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d4910c072b5</guid>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[pure-storage]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[flashblade]]></category>
            <dc:creator><![CDATA[jboothomas]]></dc:creator>
            <pubDate>Thu, 10 Aug 2023 17:11:06 GMT</pubDate>
            <atom:updated>2024-11-27T10:26:26.936Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog I will go over how to use S3 storage on a Pure Storage Flashblade with Trino the fast distributed SQL query engine for big data.</p><p>I deploy Trino using the helm chart and provide a values.yaml file with the following configuration:</p><pre>additionalCatalogs:<br>  lakehouse: |-<br>    connector.name=hive<br>    hive.metastore.uri=thrift://hivems-hive-metastore.analytics.svc.local:9083    <br>    hive.s3.aws-access-key=PSFB....BJEIA<br>    hive.s3.aws-secret-key=A121....eJOEN<br>    hive.s3.endpoint=192.168.2.2<br>    hive.s3.ssl.enabled=false<br></pre><p>This is pointing to my hive-metastore server see this <a href="https://jboothomas.medium.com/hive-metastore-on-k8s-with-s3-external-table-607102a11e56">blog post</a> for more information on setting that up. I then edit the Trino service to switch from ClusterIP to NodePort so as to facilitate external access.</p><p>As usual I use the helm install command:</p><pre>helm -n analytics install trino trino/trino  -f values.yaml</pre><p>On a linux client with the trino-cli installed, I use the following command to connect to my in Kubernetes running instance, and list the current catalogs available:</p><pre>$ ./trino-cli-422-executable.jar --server http://10.225.114.50:32140<br>trino&gt; show catalogs;<br>  Catalog  <br>-----------<br> hive <br> system    <br> tpcds     <br> tpch      <br>(4 rows)<br><br>Query 20230810_122520_00000_gb9kf, FINISHED, 2 nodes<br>Splits: 68 total, 68 done (100.00%)<br>1.15 [0 rows, 0B] [0 rows/s, 0B/s]<br><br>trino&gt;</pre><p>I can then select my hive source and check the available tables:</p><pre>trino&gt; use hive.default;<br>USE<br>trino:default&gt;  show tables;<br>     Table     <br>---------------<br> nyctaxi_table <br>(1 row)<br><br>Query 20230810_140256_00004_uapkp, FINISHED, 3 nodes<br>Splits: 68 total, 68 done (100.00%)<br>0.45 [1 rows, 30B] [2 rows/s, 67B/s]<br><br>trino:default&gt;</pre><p>Note that to see the available schemas you can use:</p><pre>trino&gt; show schemas from hive;<br>       Schema       <br>--------------------<br> default            <br> information_schema <br>(2 rows)<br><br>Query 20230810_152954_00003_a45jd, FINISHED, 3 nodes<br>Splits: 68 total, 68 done (100.00%)<br>0.61 [2 rows, 35B] [3 rows/s, 57B/s]</pre><p>To see the table schema you can use:</p><pre>trino:default&gt; describe nyctaxi;<br>        Column         |     Type     | Extra | Comment <br>-----------------------+--------------+-------+---------<br> vendorid              | bigint       |       |         <br> tpep_pickup_datetime  | timestamp(3) |       |         <br> tpep_dropoff_datetime | timestamp(3) |       |         <br> passenger_count       | double       |       |         <br> trip_distance         | double       |       |         <br> ratecodeid            | double       |       |         <br> store_and_fwd_flag    | varchar      |       |         <br> pulocationid          | bigint       |       |         <br> dolocationid          | bigint       |       |         <br> payment_type          | bigint       |       |         <br> fare_amount           | double       |       |         <br> extra                 | double       |       |         <br> mta_tax               | double       |       |         <br> tip_amount            | double       |       |         <br> tolls_amount          | double       |       |         <br> improvement_surcharge | double       |       |         <br> total_amount          | double       |       |         <br>(17 rows)<br><br>Query 20230810_163505_00104_a45jd, FINISHED, 3 nodes<br>Splits: 68 total, 68 done (100.00%)<br>0.28 [17 rows, 1.05KB] [60 rows/s, 3.72KB/s]<br><br></pre><p>I can now run various queries on the dataset, please note this is from a very limited lab k8s cluster with low resources and network connectivity, so performance was not the aim:</p><pre>trino:default&gt; select count(*) from nyctaxi;<br>   _col0   <br>-----------<br> 899294289 <br>(1 row)<br><br>Query 20230815_132013_00029_4suvq, FINISHED, 1 node<br>Splits: 343 total, 343 done (100.00%)<br>1.04 [899M rows, 3.56MB] [865M rows/s, 3.43MB/s]<br><br>trino:default&gt; select * from nyctaxi WHERE tolls_amount &gt; 100 order by tolls_amount desc limit 10;<br> vendorid |  tpep_pickup_datetime   |  tpep_dropoff_datetime  | passenger_count | trip_distance | ratecodeid | store_and_fwd_flag | pulocationid | dolocationid | payment_type | fare_amount | extra | mta<br>----------+-------------------------+-------------------------+-----------------+---------------+------------+--------------------+--------------+--------------+--------------+-------------+-------+----<br>        2 | 2017-07-03 17:15:15.000 | 2017-07-03 17:35:57.000 |               1 |          9.74 |          1 | N                  |          138 |          107 |            2 |        27.5 |   1.0 |    <br>        2 | 2015-12-12 00:17:39.000 | 2015-12-12 01:14:18.000 |               1 |         38.48 |          5 | N                  |           68 |          265 |            2 |       200.0 |   0.0 |    <br>        1 | 2016-12-29 07:46:33.000 | 2016-12-29 08:03:36.000 |               1 |           4.7 |          1 | N                  |          151 |          223 |            2 |        16.5 |   0.0 |    <br>        1 | 2014-08-15 10:37:42.000 | 2014-08-15 11:07:21.000 |               1 |          10.0 |          1 | N                  |          230 |          138 |            3 |        32.0 |   0.0 |    <br>        1 | 2015-01-06 18:27:38.000 | 2015-01-06 19:04:04.000 |               2 |          18.5 |          2 | N                  |          264 |          264 |            2 |        52.0 |   0.0 |    <br>        1 | 2016-03-14 15:16:32.000 | 2016-03-14 16:27:11.000 |               1 |          18.5 |          2 | Y                  |          132 |          230 |            3 |        52.0 |   0.0 |    <br>        1 | 2016-05-02 09:10:21.000 | 2016-05-02 09:58:00.000 |               1 |          18.0 |          2 | N                  |          229 |          132 |            3 |        52.0 |   0.0 |    <br>        1 | 2017-11-28 23:24:24.000 | 2017-11-29 00:09:00.000 |               1 |           6.2 |          1 | N                  |          246 |          112 |            3 |        26.5 |   0.5 |    <br>        1 | 2014-09-14 12:37:44.000 | 2014-09-14 12:49:49.000 |               2 |           1.4 |          1 | N                  |          186 |          170 |            3 |         9.5 |   0.0 |    <br>        1 | 2015-11-20 21:35:41.000 | 2015-11-20 22:08:29.000 |               1 |           8.5 |          1 | N                  |          264 |          264 |            3 |        30.5 |   0.5 |    <br>(10 rows)<br><br>Query 20230815_131646_00028_4suvq, FINISHED, 1 node<br>Splits: 353 total, 353 done (100.00%)<br>2.77 [487M rows, 6.36GB] [176M rows/s, 2.3GB/s]</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d4910c072b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hive-metastore on K8S with S3 external table]]></title>
            <link>https://jboothomas.medium.com/hive-metastore-on-k8s-with-s3-external-table-607102a11e56?source=rss-3f68706e8d2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/607102a11e56</guid>
            <category><![CDATA[hive]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[flashblade]]></category>
            <category><![CDATA[pure-storage]]></category>
            <dc:creator><![CDATA[jboothomas]]></dc:creator>
            <pubDate>Thu, 10 Aug 2023 16:55:07 GMT</pubDate>
            <atom:updated>2023-08-10T16:55:07.118Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog I will cover how to setup Hive metastore on K8S and then leverage external S3 datasets.</p><h3>Installation</h3><p>In order to deploy Hive components on the Kubernetes cluster I first add the required helm chart repo:</p><pre>$ helm repo add bigdata-gradiant https://gradiant.github.io/bigdata-charts/<br>$ helm repo update</pre><p>I can then search the new repo for the available helm charts, at the time of writing these are:</p><pre>$ helm search repo bigdata-gradiant<br>NAME                              CHART VERSION APP VERSION DESCRIPTION                                       <br>bigdata-gradiant/hbase            0.1.6         2.0.1       HBase is an open-source non-relational distribu...<br>bigdata-gradiant/hdfs             0.1.10        2.7.7       The Apache Hadoop software library is a framewo...<br>bigdata-gradiant/hive             0.1.6         2.3.6       The Apache Hive ™ data warehouse software facil...<br>bigdata-gradiant/hive-metastore   0.1.3         2.3.6       The Apache Hive ™ data warehouse software facil...<br>bigdata-gradiant/jupyter          0.1.11        6.0.3       Helm for jupyter single server with pyspark sup...<br>bigdata-gradiant/kafka-connect-ui 0.1.0         0.9.7       Helm for Landoop/kafka-connect-ui                 <br>bigdata-gradiant/opentsdb         0.1.7         2.4.0       Store and serve massive amounts of time series ...<br>bigdata-gradiant/spark-standalone 0.1.0         2.4.4       Apache Spark™ is a unified analytics engine for...</pre><p>So as to link trino to some S3 datasets I will be deploying a Hive metastore:</p><pre>$ helm install hivems bigdata-gradiant/hive-metastore -n analytics<br>NAME: hivems<br>LAST DEPLOYED: Thu Aug 10 10:21:47 2023<br>NAMESPACE: analytics<br>STATUS: deployed<br>REVISION: 1<br>TEST SUITE: None</pre><p>I check that my pods have started correctly within Kubernetes:</p><pre>$ kubectl -n analytics get pods<br>NAME                                                READY   STATUS   <br>...                0             42m<br>hivems-hive-metastore-0                             1/1     Running   <br>hivems-postgresql-0                                 1/1     Running  <br>...</pre><p>I then copy out the created configmap and append the following to the data hive-site.xml section (replace with your S3 endpoint values):</p><pre>$ kubectl -n analytics get configmap hivems-hive-metastore -o yaml  &gt; hivems-hive-metastore.yaml<br>$ vi hivems-hive-metastore.yaml <br><br>### I MAKE THE FOLLOWING CHANGE/ADDITION ###<br>data:<br>  hive-site.xml: |<br>    &lt;?xml version=&quot;1.0&quot;?&gt;<br>    &lt;?xml-stylesheet type=&quot;text/xsl&quot; href=&quot;configuration.xsl&quot;?&gt;<br>    &lt;configuration&gt;<br>        &lt;property&gt;<br>          &lt;name&gt;fs.s3a.endpoint&lt;/name&gt;<br>          &lt;value&gt;192.168.2.2&lt;/value&gt; <br>        &lt;/property&gt;<br>        &lt;property&gt;<br>          &lt;name&gt;fs.s3a.access.key&lt;/name&gt;<br>          &lt;value&gt;PSFB....JEIA&lt;/value&gt; <br>        &lt;/property&gt;<br>        &lt;property&gt;<br>          &lt;name&gt;fs.s3a.secret.key&lt;/name&gt;<br>          &lt;value&gt;A121....eJOEN&lt;/value&gt; <br>        &lt;/property&gt;<br>        &lt;property&gt;<br>          &lt;name&gt;fs.s3a.connection.ssl.enabled&lt;/name&gt;<br>          &lt;value&gt;false&lt;/value&gt;<br>        &lt;/property&gt;</pre><p>Note: I had to create a new container image to include the missing hadoop-aws-2.7.4.jar file this can be obtained from my docker repo jboothomas/hive-metastore-s3:v6. I then simply provided this as the image to use for the hive-metastore deployment.</p><h3>Table creation</h3><p>To create an external table I exec into the hive metastore pod and connect to hive:</p><pre>$ kubectl -n analytics exec -it hivems-hive-metastore-0 - /bin/sh<br># hive<br>SLF4J: Class path contains multiple SLF4J bindings.<br>SLF4J: Found binding in [jar:file:/opt/hive/lib/log4j-slf4j-impl-2.6.2.jar!/org/slf4j/impl/StaticLoggerBinder.class]<br>SLF4J: Found binding in [jar:file:/opt/hadoop-2.7.4/share/hadoop/common/lib/slf4j-log4j12-1.7.10.jar!/org/slf4j/impl/StaticLoggerBinder.class]<br>SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.<br>SLF4J: Actual binding is of type [org.apache.logging.slf4j.Log4jLoggerFactory]<br><br>Logging initialized using configuration in jar:file:/opt/hive/lib/hive-common-2.3.2.jar!/hive-log4j2.properties Async: true<br>Hive-on-MR is deprecated in Hive 2 and may not be available in the future versions. Consider using a different execution engine (i.e. spark, tez) or using Hive 1.X releases.<br>hive&gt; </pre><p>Now I can create my external table:</p><pre>create external table if not exists nyctaxi(<br>    VendorID bigint,<br>    tpep_pickup_datetime timestamp,<br>    tpep_dropoff_datetime timestamp,<br>    passenger_count double,<br>    trip_distance double,<br>    RatecodeID double,<br>    store_and_fwd_flag string,<br>    PULocationID bigint,<br>    DOLocationID bigint,<br>    payment_type bigint,<br>    fare_amount double,<br>    extra double,<br>    mta_tax double,<br>    tip_amount double,<br>    tolls_amount double,<br>    improvement_surcharge double,<br>    total_amount double<br>    )<br>    STORED AS PARQUET<br>    LOCATION &#39;s3a://nyctaxi/&#39;;<br>Time taken: 2.756 seconds</pre><p>From this point onwards i can leverage various analyics tools and point to my hive-metastore service to run queries against this table (for example: trino).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=607102a11e56" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>