<?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 Michele Maria Miscione on Medium]]></title>
        <description><![CDATA[Stories by Michele Maria Miscione on Medium]]></description>
        <link>https://medium.com/@michelemiscione?source=rss-51de94acaf95------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7L9AKIH9mNNRa1usXTv8rw.png</url>
            <title>Stories by Michele Maria Miscione on Medium</title>
            <link>https://medium.com/@michelemiscione?source=rss-51de94acaf95------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 19:53:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@michelemiscione/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[Leveraging Oracle Vector Store and LLMs for Advanced Customer Lookalike Segmentation]]></title>
            <link>https://medium.com/@michelemiscione/customer-lookalike-by-llm-and-oracle-vector-store-d3d62d10fb17?source=rss-51de94acaf95------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3d62d10fb17</guid>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[oracle-23ai]]></category>
            <category><![CDATA[marketing-segmentation]]></category>
            <category><![CDATA[llm-applications]]></category>
            <category><![CDATA[genai]]></category>
            <dc:creator><![CDATA[Michele Maria Miscione]]></dc:creator>
            <pubDate>Tue, 21 Jan 2025 14:54:36 GMT</pubDate>
            <atom:updated>2025-01-21T14:57:10.388Z</atom:updated>
            <content:encoded><![CDATA[<h4>Unlock advanced customer segmentation techniques by Oracle converged database 23ai capabilities.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*niZceHqrw97DLvA2kJpKAA.png" /></figure><h3>Introduction</h3><p>Imagine being able to personalize every marketing campaign with such precision that it significantly boosts ROI, identifying similar customers with just a few clicks. This is the potential unlocked by generative AI and large language models (LLMs). According to McKinsey, generative AI has the power to transform numerous business functions, with marketing standing out as one of the areas with the highest potential for value creation and cost reduction.</p><p>The ability of LLMs to analyze, segment, and comprehend complex data opens up new opportunities to enhance campaign personalization and effectiveness. For instance, LLMs can generate tailored content for communication or optimize fundamental activities like customer segmentation and semantic similarity searches among profiles.</p><p>In this article, we will explore a practical example of leveraging similarity search through the Oracle 23ai converged database to identify customer lookalikes. We’ll dive into advanced techniques such as vector representation of data and Oracle’s native capabilities to create more effective customer segments, delivering tangible benefits to marketing strategies.</p><h3>Use Case and context</h3><p>Managing customer data for enterprises is challenging due to fragmented data sources and the need to integrate data in motion with data at rest. The Oracle Data Platform excels in supporting modern distributed data architectures like Data Mesh. Check out <a href="https://medium.com/@datagreenhouseteam/demystify-data-mesh-with-oracle-technology-5a277e59b41b">this article if you want to explore this topic further</a>. For this example, I’ll skip the details of building a 360-degree customer view that’s flexible enough to support marketing and CRM functions. Instead, let’s assume the customer data is already available in the Oracle database, following the simplified schema below. This scenario is quite common, and in other cases, the Oracle Data Platform provides everything needed to make a 360-degree customer view achievable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qOg1BEHTUo2B4ZbyHt-qpg.png" /><figcaption>Simplified Customer Schema</figcaption></figure><p>Data could be fully relational or include additional elements, like JSON data or unstructured data such as customer service requests (SRs) or channel navigation logs. In these scenarios, a converged database is a game-changer, making it easier to handle diverse data types while reducing data movement. This not only simplifies workflows but also eliminates consistency issues that often occur during data preparation when data is copied and processed.</p><p>As well LLMs make it easier to work with data that was previously challenging to use or required extensive pre-processing and may provide several benefits. For instance, when performing customer segmentation with clustering techniques like k-means, data preparation often involves encoding categorical variables into a format compatible with machine learning algorithms. This is typically done using techniques like one-hot encoding to enhance predictive accuracy. So traditional approaches suffer of many common limitations:</p><ul><li><strong>Hand-crafted feature engineering</strong> <strong>is a major challenge</strong> in industrial machine learning due to its reliance on domain expertise, extensive experimentation, and ongoing maintenance. This approach limits scalability, as models cannot be easily automated or updated due to manual engineering need. The challenge intensifies when working with unstructured or volatile data sources, like application logs, which often lack clear documentation and have complex semantics.</li><li><strong>Event sequence aggregation simplifies customer behavior profiles</strong>, converting event sequences (e.g., clicks, purchases) into fixed-length features like averages or totals for compatibility with traditional machine learning. However, this often sacrifices temporal dependencies, which can theoretically be preserved through complex feature engineering — a challenging and time-intensive task.</li><li><strong>Disconnect from content data </strong>because of historically, behavior and content-based personalization must be analyzed separately. However, deep learning now enables more efficient personalization by unifying embeddings from behavioral, textual, and image data.</li><li><strong>Traditional approaches rely on historical data </strong>and assume a static environment where past patterns inform future actions. This poses a significant limitation in modern, real-time customer experiences, making these methods unsuitable for dynamic environments with frequent updates, such as short-term deals, new products, or news posts.</li></ul><p>Additionally, the large vector embedding dimensions generated by LLM allow for greater precision in detecting small variations in the data. As a result, when this rich information is fed into a K-means model, it delivers more accurate predictions.</p><p>Coming back to the today topic we will see how to perform semantic search over customer data leveraging the Oracle 23ai database and Oracle OCI GenAI service.</p><h3>How to create Customer Vector Space in a while</h3><p>Building upon our earlier discussion, let’s consider customer data stored in a relational model.To utilize this data with an embedding model, we need to present it as a document. Traditional methods like ETL processes or leveraging Oracle’s native JSON support could achieve this transformation. However, to attain zero-ETL and eliminate data movement, Oracle Database 23ai’s JSON Relational Duality offers an optimal solution also in term of ease. Specifically, Duality Views allow data stored in relational tables to be used as a collection of JSON documents using intuitive GraphQL syntax, facilitating flexible and efficient data manipulation without the complexities of Object-Relational Mappings (ORMs). Duality view ease also the need to join different tables to create a unique JSON document with the whole customer view 360.</p><h4>Create the customer 360 document</h4><p>From theory to practice, let’s explore how to create a duality view based on the database schema we’ve introduced.</p><pre>create or replace json relational duality view customer_360 as<br>select json {&#39;_id&#39;        : c.CUST_ID,<br>             &#39;lastname&#39;   : c.LAST_NAME,<br>             &#39;firstname&#39;  : c.FIRST_NAME,<br>             &#39;address&#39;    : c.STREET_ADDRESS||&#39; &#39;||c.CITY||&#39; &#39;||c.STATE_PROVINCE||&#39; &#39;||c.COUNTRY,<br>             &#39;lifetime&#39;   : c.YRS_CUSTOMER,<br>             &#39;profile&#39; :<br>               [ select json {&#39;customer_id&#39;   : p.CUST_ID,<br>                              &#39;gender&#39;        : p.GENDER,<br>                              &#39;education&#39;     : p.EDUCATION,<br>                              &#39;householdsize&#39; : p.HOUSEHOLD_SIZE,<br>                              &#39;maritalstatus&#39; : p.MARITAL_STATUS}<br>                 from   CRM_CUSTOMER_PROFILE p with insert update delete<br>                 where  c.CUST_ID = p.CUST_ID ]}<br>from CRM_CUSTOMER_CONTACT c with insert update delete;</pre><p>Just this to present and interact with the customer 360 data through GraphQL so now we can see relational data as a JSON document.</p><pre>select * from customer_360 where rownum &lt; 2;<br><br>{<br> &quot;_id&quot;: 1171717,<br> &quot;address&quot;: &quot; Japan 日本 Japan&quot;,<br> &quot;lifetime&quot;: 10,<br> &quot;profile&quot;: [<br>  {<br>   &quot;customer_id&quot;: 1171717,<br>   &quot;gender&quot;: &quot;Male&quot;,<br>   &quot;education&quot;: &quot;Doctorate&quot;,<br>   &quot;householdsize&quot;: 1,<br>   &quot;maritalstatus&quot;: &quot;S&quot;<br>  }<br> ],<br> &quot;_metadata&quot;: {<br>  &quot;etag&quot;: &quot;B6D7C78E7360A352AE305796A59BFD9C&quot;,<br>  &quot;asof&quot;: &quot;0000283759A3DB6B&quot;<br> }<br>}</pre><p>The JSON Relational Duality feature offers more than just data transformation from relation to JSON; it enables application developers to interact with data seamlessly through Oracle REST Data Services (ORDS). While this topic is significant and warrants further exploration, it falls outside the scope of this article. For more information you can consult the official documentation or refer to <a href="https://blogs.oracle.com/database/post/json-relational-duality-app-dev">this Oracle blog post</a>.</p><p>Before to go forward to the Customer2Vec transformation by LLM I decided to clean the customer view 360 from some data not relevant for this first lookalike test what is my target. To do that I could rebuild the duality view with less information but I prefer to build a view on top to the duality view also because in a real case the duality view with person information could be needed from external application or to show customer_id mapping. So I created this additional view on top to the duality view:</p><pre>create or replace view customer_360_formatted as<br>SELECT c.data, <br>       CV.*, <br>       json_object(<br>        KEY &#39;customer_id&#39; IS cv.id,<br>        KEY &#39;address&#39; IS cv.address,<br>        KEY &#39;lifetime&#39; IS cv.lifetime,<br>        KEY &#39;profile&#39; IS cv.profile<br>       ) json_for_embetting<br>  FROM customer_360 c,<br>       json_table(c.data, &#39;$&#39;<br>         COLUMNS (id VARCHAR2 PATH &#39;$._id&#39;,<br>                  address VARCHAR2 PATH &#39;$.address&#39;,<br>                  lifetime INTEGER PATH &#39;$.lifetime&#39;,<br>                  profile VARCHAR2 FORMAT JSON<br>                            PATH &#39;$.profile&#39;)<br>                 ) AS &quot;CV&quot;;</pre><p>And this is the final cv360 document for the customer2vec transformation. Note that my collection have 148.130 customers and this to provide a non-trivial example, consider also the need to embed the data massively.</p><pre>select * from customer_360 where rownum &lt;2;<br><br>{<br> &quot;_id&quot;: 1182099,<br> &quot;address&quot;: &quot; Japan Japan Japan&quot;,<br> &quot;lifetime&quot;: 6,<br> &quot;profile&quot;: [<br>  {<br>   &quot;customer_id&quot;: 1182099,<br>   &quot;gender&quot;: &quot;Male&quot;,<br>   &quot;education&quot;: &quot;Bachelors&quot;,<br>   &quot;householdsize&quot;: 1,<br>   &quot;maritalstatus&quot;: &quot;S&quot;<br>  }<br> ]<br>}</pre><h4>Documents chunking and embedding</h4><p>The final operation is to chunk the documents in the collection and build the array of vector_t to then ebbed through the use of the embedding LLM. In this case as well, Oracle 23ai capabilities simplify chunking by utilizing the DBMS_VECTOR_CHAIN.UTL_TO_CHUNKS function. We&#39;ll review the code shortly, but it&#39;s worth mentioning that in this initial example, I won&#39;t go into detail about the chunking process, mainly because the prepared JSON is short enough to be embedded without the need for chunking. So the following diagram recap the steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*wQ0O-KKrpy06hMpZxauiYA.png" /><figcaption>from relational schema to array of json documents chunks</figcaption></figure><p>Now we have to build the customer vector space leveraging the LLM. The aim is described in the follow schema and leverage again the DBMS_VECTOR.UTL_TO_EMBEDDINGS function that can support severl type of embedding LLMs to transform the chunks in the embedding vectors. Oracle database also offer the to import the LLM model for maximum security and zero data movement. Please refer to the official <a href="https://docs.oracle.com/en/database/oracle/oracle-database/23/vecse/supported-third-party-provider-operations-and-endpoints.html#VECSE-GUID-BE3EE403-CD10-4708-A15F-EFB1FA69DF09">Oracle 23ai documentation</a> to see all the available options and third-party providers currently supported. For this example I used the Cohere embed-multilingual-v3.0 embedding model hosted on the OCI GenAI service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*nFw8Tib3BB9rtQTTeFS51w.png" /><figcaption>from array of json documents chunks to a vector space in the vector store</figcaption></figure><p>Let’s move again from theory to practice by demonstrating how to create and populate a vector store with embeddings computed for each JSON document chunk.</p><pre>CREATE TABLE crm_customer_cv360embedding (<br>    customer_id NUMBER not null, <br>    chunk_id NUMBER not null, <br>    embed_id NUMBER, <br>    chunk_offset NUMBER, <br>    chunk_length NUMBER, <br>    embed_data VARCHAR2(4000), <br>    embed_vector VECTOR,<br>    CONSTRAINT crm_customer_cv360embedding_pk <br>    PRIMARY KEY (customer_id, chunk_id)<br>);<br><br>create vector index customer_hnsw_idx <br>    on  crm_customer_cv360embedding(embed_vector) <br>organization inmemory neighbor graph distance COSINE <br>with target accuracy 95;</pre><p>First of all we have to create the table to store the vector embeddings and the then we will use to perform the semantic search. Vector data type is natively managed in the Oracle database since the 23ai version, extending the converged database capabilities. To be ready for an efficient search I also defined an index on the table. Oracle AI Vector Search supports the following categories of vector indexing methods based on approximate nearest-neighbors (ANN) search:</p><ul><li>In-Memory Neighbor Graph Vector Index (HNSW)</li><li>Neighbor Partition Vector Index (IVF)</li></ul><p>HNSW graph based in-memory index are very efficient for vector approximate similarity search. Because my aim is to leverage semantic search to perform customer lookalike I decided to use this type of index.</p><p>We’re now ready to calculate the embedding vectors and store them in the table. Given the substantial size of the customer collection, we need to calculate the embeddings in batches. Otherwise, we would have to make a separate call to the LLM model for each customer, leading to excessive processing time and potential issues with throughput limits. This is the reason to build the v_utl_chunk array collecting the chunks related to the whole customer base before to call the DBMS_VECTOR.UTL_TO_EMBEDDINGS to calculate the embeddings.</p><pre><br>DECLARE<br>    v_provider_params       CLOB;<br>    v_chunk_params          CLOB;<br>    v_idx                   NUMBER := 1;<br>    c_idx                   NUMBER;<br>    v_embeddings            VECTOR_ARRAY_T;<br>    v_text                  CLOB;<br>    v_chunks                VECTOR_ARRAY_T;<br>    l_utl_chunk             VECTOR_ARRAY_T;<br><br>    CURSOR customer360_to_embed_cur is<br>    select json_for_embetting from customer_360_formatted; <br>    customer360_to_embed customer360_to_embed_cur%ROWTYPE;<br>BEGIN<br><br>    v_provider_params := &#39;{<br>            &quot;provider&quot;: &quot;OCIGenAI&quot;,<br>            &quot;credential_name&quot;: &quot;OCI_GENAI_CRED&quot;,<br>            &quot;url&quot;: &quot;https://inference.generativeai.us-chicago-1.oci.oraclecloud.com/20231130/actions/embedText&quot;,<br>            &quot;model&quot;: &quot;cohere.embed-multilingual-v3.0&quot;,<br>            &quot;batch_size&quot; : &quot;96&quot;<br>            }&#39;;<br>    v_chunk_params := &#39;{<br>            &quot;by&quot;:&quot;characters&quot;,<br>            &quot;max&quot;:&quot;400&quot;, <br>            &quot;normalize&quot;:&quot;all&quot;<br>            }&#39;;<br><br>    v_chunks := VECTOR_ARRAY_T();<br>    v_idx := 1;<br>    c_idx :=1;<br><br>    FOR customer360_to_embed IN customer360_to_embed_cur<br>    LOOP<br>            EXIT WHEN customer360_to_embed_cur%NOTFOUND;<br>            c_idx := c_idx+1;<br><br>            select to_clob(customer360_to_embed.json_for_embetting)<br>              into v_text<br>              from dual;<br><br>            l_utl_chunk := DBMS_VECTOR_CHAIN.UTL_TO_CHUNKS(v_text, json(v_chunk_params));<br>            for i in 1 .. l_utl_chunk.count loop<br>                v_chunks.EXTEND(1);<br>                v_chunks(v_idx) := l_utl_chunk(i);<br>                v_idx:= v_idx+1;<br>            end loop;<br>            <br>    END LOOP;<br><br>    v_embeddings := dbms_vector.UTL_TO_EMBEDDINGS(v_chunks, json(v_provider_params));<br>    <br>    drop index customer_hnsw_idx;<br><br>    v_idx := 1;<br>    DBMS_OUTPUT.PUT_LINE(&#39;Total number of customer: &#39;||c_idx||&#39;. Total number of embeddings: &#39;||to_char(v_embeddings.count));<br>    for i in 1 .. v_embeddings.count loop<br><br>        INSERT INTO crm_customer_cv360embedding (CUSTOMER_ID, CHUNK_ID, EMBED_ID, CHUNK_OFFSET, CHUNK_LENGTH, EMBED_DATA, EMBED_VECTOR)<br>             VALUES(<br>                    JSON_VALUE(JSON_VALUE(v_embeddings(v_idx), &#39;$.embed_data&#39;),&#39;$.customer_id&#39;), --customer_id<br>                    JSON_VALUE(v_chunks(v_idx), &#39;$.chunk_id&#39;), --chunk_id<br>                    JSON_VALUE(v_embeddings(v_idx), &#39;$.embed_id&#39;), --embed_id<br>                    JSON_VALUE(v_chunks(v_idx), &#39;$.chunk_offset&#39;), --chunk_offset<br>                    JSON_VALUE(v_chunks(v_idx), &#39;$.chunk_length&#39;), --chunk_length<br>                    JSON_VALUE(v_embeddings(v_idx), &#39;$.embed_data&#39;), --embed_data<br>                    to_vector(JSON_VALUE(v_embeddings(v_idx), &#39;$.embed_vector&#39; RETURNING CLOB)) --embed_vector<br>             )<br>        ; <br><br>        v_idx := v_idx +1;<br><br>    END LOOP;<br>    COMMIT;<br><br>    create vector index customer_hnsw_idx <br>        on crm_customer_cv360embedding(embed_vector) <br>        organization inmemory neighbor graph distance COSINE <br>        with target accuracy 95;<br><br>    DBMS_OUTPUT.PUT_LINE(&#39;Process END.&#39;);<br><br>END;</pre><p>Finally we obtain from the embeddings the customer vector space stored in the crm_customer_cv360embedding table, which will be base for the similarity search or could be the input of our Kmeans model. The statement execution taken 00:59:34.063 for 148.130 customers/chunks based on OCI GenAI on demand service and OCI Autonomous Datawarehouse 2 ECPUs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*KnCyJVW8x7niY_PH-AI8IA.png" /><figcaption>Customer vector space and OCI GenAI embeddings representation</figcaption></figure><h3>Lookalike by semantic search in paractice</h3><p>By the vector space just created we can now perform the semantic search by the Oracle AI Vector Search database capability. AI Vector Search enable to <strong>query data based on semantics (meaning) rather than just keywords.</strong> This allows you to find information that is conceptually similar to your search, even if the exact words don’t match. This is tipically used in RAG architecture to provide fresh and trusted information to the generative LLM as context in order to generate grounded and more accurate answer. In this case we are using AI Vector Search to find customer semantically similar.</p><p>But what does “semantically similar customers” mean? Imagine you want to create a segment of customers similar to a specific persona with certain characteristics, such as having a “Doctorate” level of education. Based on semantic similarity derived from LLM embeddings, a vector search might also retrieve customers with an education level of “Master’s.” Semantic similarity from LLM embeddings can enhance customer segmentation by identifying individuals with similar characteristics, even if they are not identical. However, the example could be expanded to illustrate additional possibilities, such as similarity in behavior, interests, geography, demographics, and more. These are just a few examples, but exploring this concept in depth is beyond the scope of this article. Here, the focus is on demonstrating how to effectively leverage the features of Oracle 23ai.</p><p>So, how to perform lookalike? By the following select statement where we use as prompt the string that represent a persona with the set of attributes: <em>‘{“gender”:”Male”,”education”:”Doctorate”,”householdsize”:1,”maritalstatus”:”M”}’</em>. By the vector_distance function we will then see the cosine similarity score between the persona embedding vector and the embedding vector in the customer vector space we build and have a ranked list of similar customers where the score can vary between 0 (most similar vectors) and 2 (opposite vectors). For additional information look to the <a href="https://docs.oracle.com/en/database/oracle/oracle-database/23/vecse/cosine-similarity.html">official documentation</a>.</p><pre><br>select rownum rank_id,<br>       ce.customer_id,<br>       ce.chunk_id,<br>       ce.embed_data,<br>       vector_distance(<br>          ce.embed_vector,<br>          (<br>             select to_vector(et.embed_vector) embed_vector<br>               from dbms_vector_chain.utl_to_embeddings(<br>                &#39;{&quot;gender&quot;:&quot;Male&quot;,&quot;education&quot;:&quot;Doctorate&quot;,&quot;householdsize&quot;:1,&quot;maritalstatus&quot;:&quot;M&quot;}&#39;<br>                ,<br>                json(<br>                      &#39;{&quot;provider&quot;: &quot;OCIGenAI&quot;, <br>                            &quot;credential_name&quot;: &quot;OCI_GENAI_CRED&quot;, <br>                            &quot;url&quot;: &quot;https://inference.generativeai.us-chicago-1.oci.oraclecloud.com/20231130/actions/embedText&quot;, <br>                            &quot;model&quot;: &quot;cohere.embed-multilingual-v3.0&quot;}&#39;<br>                   )<br>             ) q,<br>                    json_table(q.column_value,<br>                       &#39;$[*]&#39;<br>                   columns(<br>                       embed_id number path &#39;$.embed_id&#39;,<br>                       embed_data varchar2(4000) path &#39;$.embed_data&#39;,<br>                       embed_vector clob path &#39;$.embed_vector&#39;<br>                   )<br>                )<br>             et<br>          ),<br>          cosine<br>       ) as vector_distance<br>  from crm_customer_cv360embedding ce<br> order by vector_distance<br> fetch first 20 rows only;</pre><h3>Lookalike examples by similarity search</h3><p>In order to streamline the testing process, I have implemented a function that encapsulates the specified select statement.</p><pre>CREATE TYPE customer_lal_dtype AS OBJECT (<br>  customer_id       NUMBER,<br>  gender            VARCHAR2(50),<br>  education         VARCHAR2(50),<br>  household_size    VARCHAR2(10),<br>  marital_status    VARCHAR2(50),<br>  full_desc         VARCHAR2(400),<br>  vector_distance   NUMBER<br>);<br>/<br><br>CREATE TYPE customer_lal_dtype_tab IS TABLE OF customer_lal_dtype;<br>/<br><br><br>CREATE OR REPLACE FUNCTION customer_lookalike (p_rows IN NUMBER, p_prompt IN CLOB) RETURN customer_lal_dtype_tab IS<br>        l_cust_lal_dtype_tab customer_lal_dtype_tab;<br>BEGIN<br><br>         select customer_lal_dtype(<br>                                        customer_id,<br>                                        gender,<br>                                        education,<br>                                        householdsize,<br>                                        maritalstatus,<br>                                        full_desc,<br>                                        vector_distance<br>                )<br>                bulk collect into l_cust_lal_dtype_tab<br>                from (<br>                select to_number(ce.customer_id) customer_id,<br>                        json_value(ce.embed_data,<br>                                    &#39;$.profile[0].gender&#39; RETURNING VARCHAR2(50)) gender,<br>                        json_value(ce.embed_data,<br>                                    &#39;$.profile[0].education&#39; RETURNING VARCHAR2(50)) education,<br>                        json_value(ce.embed_data,<br>                                    &#39;$.profile[0].householdsize&#39; RETURNING VARCHAR2(10)) householdsize,<br>                        json_value(ce.embed_data,<br>                                    &#39;$.profile[0].maritalstatus&#39; RETURNING VARCHAR2(50)) maritalstatus,<br>                        to_clob(ce.embed_data) full_desc,<br>                        vector_distance(<br>                            ce.embed_vector,<br>                            (<br>                                select to_vector(et.embed_vector) embed_vector<br>                                from dbms_vector_chain.utl_to_embeddings(<br>                                p_prompt,<br>                                json(<br>                                        &#39;{&quot;provider&quot;: &quot;OCIGenAI&quot;, <br>                                                            &quot;credential_name&quot;: &quot;OCI_GENAI_CRED&quot;, <br>                                                            &quot;url&quot;: &quot;https://inference.generativeai.us-chicago-1.oci.oraclecloud.com/20231130/actions/embedText&quot;, <br>                                                            &quot;model&quot;: &quot;cohere.embed-multilingual-v3.0&quot;}&#39;<br>                                    )<br>                                ) q,<br>                                    json_table(q.column_value,<br>                                        &#39;$[*]&#39;<br>                                    columns(<br>                                        embed_id number path &#39;$.embed_id&#39;,<br>                                        embed_data varchar2(4000) path &#39;$.embed_data&#39;,<br>                                        embed_vector clob path &#39;$.embed_vector&#39;<br>                                    )<br>                                )<br>                                et<br>                            ),<br>                            cosine<br>                        ) vector_distance<br>                    from crm_customer_cv360embedding ce<br>                    order by vector_distance<br>                    fetch first p_rows rows only<br>                )<br>        ;<br><br>  RETURN l_cust_lal_dtype_tab;<br>END;<br>/</pre><p>So now we can quikly test our customer vector space with some lookalike examples.</p><h4>Test 1</h4><p>My first curiosity war about the exact search, so i chose as a prompt one persona having an exact match with a JSON profile in the space.</p><pre>{<br>   &quot;customer_id&quot;:&quot;1398291&quot;,<br>   &quot;address&quot;:&quot; China China China&quot;,<br>   &quot;lifetime&quot;:1,<br>   &quot;profile&quot;:[<br>      {<br>         &quot;customer_id&quot;:1398291,<br>         &quot;gender&quot;:&quot;Male&quot;,<br>         &quot;education&quot;:&quot;Doctorate&quot;,<br>         &quot;householdsize&quot;:3,<br>         &quot;maritalstatus&quot;:&quot;S&quot;<br>      }<br>   ]<br>}<br><br><br>select vector_distance, gender, education, household_size, marital_status, customer_id  <br>  from customer_lookalike(5, &#39;{&quot;customer_id&quot;:&quot;1398291&quot;,&quot;address&quot;:&quot; China China China&quot;,&quot;lifetime&quot;:1,&quot;profile&quot;:[{&quot;customer_id&quot;:1398291,&quot;gender&quot;:&quot;Male&quot;,&quot;education&quot;:&quot;Doctorate&quot;,&quot;householdsize&quot;:3,&quot;maritalstatus&quot;:&quot;S&quot;}]}&#39;);<br><br>VECTOR_DISTANCE GENDER       EDUCATION        HOUSEHOLD_ MARITAL_STATUS    CUSTOMER_ID<br>--------------- ------------ ---------------- ---------- ----------------- -----------<br> .0000104904175 Male         Doctorate        3          S                     1398291<br>    .0184630752 Male         Doctorate        3          S                     1391191<br>    .0193885565 Male         Doctorate        1          S                     1394591<br>    .0253389478 Female       Masters          2          S                     1348291<br>    .0261316895 Male         LessThanHS       2          M                     1398266<br><br>Elapsed: 00:00:11.463</pre><p>No surprise, as planned the most similar profile is the same and the vector distance score is near zero.</p><h4>Test 2</h4><p>Based on the initial query, we are seeking customers resembling a persona with the following characteristics: male, doctorate-level education, a small household, and married. Analyzing our customer base deterministically, we observe the following:</p><pre>select count(*)<br>from CRM_CUSTOMER_PROFILE<br>where gender = &#39;Male&#39;<br>  and EDUCATION = &#39;Doctorate&#39;<br>  and HOUSEHOLD_SIZE = 1<br>  and MARITAL_STATUS = &#39;M&#39;<br>;<br><br>  COUNT(*)<br>----------<br>         0</pre><p>No customers! But let’s run a similarity search to find the top 20 closest matches.</p><pre><br>select vector_distance, gender, education, household_size, marital_status, customer_id <br>from customer_lookalike(20, &#39;{&quot;gender&quot;:&quot;Male&quot;,&quot;education&quot;:&quot;Doctorate&quot;,&quot;householdsize&quot;:1,&quot;maritalstatus&quot;:&quot;M&quot;}&#39;);<br><br><br>VECTOR_DISTANCE GENDER     EDUCATION        HOUSEHOLD_ MARITAL_STATUS    CUSTOMER_ID<br>--------------- ---------- ---------------- ---------- ----------------- -----------<br>     .166589975 Male       Doctorate        3          S                     1398291<br>     .166850507 Male       Doctorate        1          S                     1422198<br>     .167356908 Male       Doctorate        5          M                     1309401<br>     .168335617 Male       Doctorate        1          S                     1308495<br>     .168499529 Male       Doctorate        1          S                     1393897<br>     .169108629 Male       Doctorate        1          S                     1394591<br>     .169346333 Male       Doctorate        5          M                     1405861<br>     .169745982 Male       Doctorate        7          M                     1282309<br>      .16983819 Male       Doctorate        7          M                     1444000<br>     .170155644 Male       Doctorate        2          M                     1109899<br>     .170495391 Male       Doctorate        7          M                     1427584<br>     .170838892 Male       Doctorate        7          M                     1421911<br>     .171526313 Male       Doctorate        3          S                     1107781<br>      .17159456 Male       Doctorate        2          M                     1390470<br>     .171912134 Male       Doctorate        1          S                     1339898<br>     .172141969 Male       Doctorate        7          M                     1272983<br>     .172248781 Male       Doctorate        5          M                     1409219<br>     .172492981 Male       Doctorate        1          S                     1427423<br>     .172540784 Male       Doctorate        7          M                     1361611<br>     .172625542 Male       Doctorate        1          S                     1109779<br><br>20 rows selected. <br><br>Elapsed: 00:00:09.953</pre><p>Good news! The vector search successfully retrieved similar customers while adhering to an exact match for sex and education level. Due to the difficulty in finding customers matching all the requested attributes, the search approximated the match between household size and marital status.</p><p>An interesting observation is that the vector distance calculation took into account the entire embedded profile, including similarities based on the address attribute. Looking at the full customer 360 results, I noticed that customers with identical addresses were scored as more similar. My interpretation is that vector search inherently forms clusters that was natively created based on overall profile concepts, retrieving the closest matches from within the same cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*T_oFZVP9jriy_96GlmSEnA.png" /></figure><h4>Test 3</h4><p>To further investigate this behavior, my third test will be a relaxed version of the previous one. In this test, I will remove the condition related to household size from the persona in order to have results.</p><pre>select count(*)<br>from CRM_CUSTOMER_PROFILE<br>where gender = &#39;Male&#39;<br>  and EDUCATION = &#39;Doctorate&#39;<br>  and MARITAL_STATUS = &#39;M&#39;<br>;<br><br>  COUNT(*)<br>----------<br>      5475<br><br>select vector_distance, gender, education, household_size, marital_status, customer_id <br>from customer_lookalike(20, &#39;{&quot;gender&quot;:&quot;Male&quot;,&quot;education&quot;:&quot;Doctorate&quot;,&quot;maritalstatus&quot;:&quot;M&quot;}&#39;);<br><br>VECTOR_DISTANCE GENDER    EDUCATION      HOUSEHOLD_ MARITAL_STATUS   CUSTOMER_ID<br>--------------- --------- -------------- ---------- ---------------- -----------<br>     .193827868 Male      Doctorate      5          M                    1405861<br>     .194780648 Male      Doctorate      1          S                    1308495<br>     .195131421 Male      Doctorate      1          S                    1393897<br>     .195284665 Male      Doctorate      2          M                    1288585<br>     .195694625 Male      Doctorate      5          M                    1309401<br>     .196106374 Male      Doctorate      7          M                    1444000<br>     .196952045 Male      Doctorate      2          M                    1109899<br>     .197562277 Male      Doctorate      7          M                    1272983<br>     .197692394 Male      Doctorate      7          M                    1282309<br>     .197775483 Male      Doctorate      5          M                    1357809<br>     .197871149 Male      Doctorate      5          M                    1409219<br>      .19805789 Male      Doctorate      5          M                    1112803<br>     .198090553 Male      Doctorate      7          M                    1421911<br>     .198121667 Male      Doctorate      7          M                    1427584<br>     .198286355 Male      Doctorate      3          S                    1248749<br>     .198436558 Male      Doctorate      2          M                    1338404<br>     .198878944 Male      Doctorate      3          S                    1240570<br>     .198882282 Male      Doctorate      7          M                    1268495<br>     .199050069 Male      Doctorate      3          S                    1398291<br>     .199146748 Male      Doctorate      3          S                    1107781<br><br>20 rows selected. <br><br>Elapsed: 00:00:12.078<br><br><br>VECTOR_DISTANCE FULL_DESC                                                                                                                  <br>--------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------<br>     .194124937 {&quot;customer_id&quot;:&quot;1405861&quot;,&quot;address&quot;:&quot; China China China&quot;,&quot;lifetime&quot;:5,&quot;profile&quot;:[{&quot;customer_id&quot;:1405861,&quot;gender&quot;:&quot;Male&quot;,&quot;education&quot;:&quot;Doctorate&quot;,&quot;householdsize&quot;:5,&quot;maritalstatus&quot;:&quot;M&quot;}]} <br>     .195079982 {&quot;customer_id&quot;:&quot;1308495&quot;,&quot;address&quot;:&quot; China China China&quot;,&quot;lifetime&quot;:6,&quot;profile&quot;:[{&quot;customer_id&quot;:1308495,&quot;gender&quot;:&quot;Male&quot;,&quot;education&quot;:&quot;Doctorate&quot;,&quot;householdsize&quot;:1,&quot;maritalstatus&quot;:&quot;S&quot;}]} <br>     .195421219 {&quot;customer_id&quot;:&quot;1393897&quot;,&quot;address&quot;:&quot; China China China&quot;,&quot;lifetime&quot;:2,&quot;profile&quot;:[{&quot;customer_id&quot;:1393897,&quot;gender&quot;:&quot;Male&quot;,&quot;education&quot;:&quot;Doctorate&quot;,&quot;householdsize&quot;:1,&quot;maritalstatus&quot;:&quot;S&quot;}]} <br>     .195656061 {&quot;customer_id&quot;:&quot;1288585&quot;,&quot;address&quot;:&quot; China China China&quot;,&quot;lifetime&quot;:4,&quot;profile&quot;:[{&quot;customer_id&quot;:1288585,&quot;gender&quot;:&quot;Male&quot;,&quot;education&quot;:&quot;Doctorate&quot;,&quot;householdsize&quot;:2,&quot;maritalstatus&quot;:&quot;M&quot;}]} <br>     .195948601 {&quot;customer_id&quot;:&quot;1309401&quot;,&quot;address&quot;:&quot; China China China&quot;,&quot;lifetime&quot;:4,&quot;profile&quot;:[{&quot;customer_id&quot;:1309401,&quot;gender&quot;:&quot;Male&quot;,&quot;education&quot;:&quot;Doctorate&quot;,&quot;householdsize&quot;:5,&quot;maritalstatus&quot;:&quot;M&quot;}]} <br>     .196422696 {&quot;customer_id&quot;:&quot;1444000&quot;,&quot;address&quot;:&quot; China China China&quot;,&quot;lifetime&quot;:10,&quot;profile&quot;:[{&quot;customer_id&quot;:1444000,&quot;gender&quot;:&quot;Male&quot;,&quot;education&quot;:&quot;Doctorate&quot;,&quot;householdsize&quot;:7,&quot;maritalstatus&quot;:&quot;M&quot;}]}<br>     .197278142 {&quot;customer_id&quot;:&quot;1109899&quot;,&quot;address&quot;:&quot; China China China&quot;,&quot;lifetime&quot;:12,&quot;profile&quot;:[{&quot;customer_id&quot;:1109899,&quot;gender&quot;:&quot;Male&quot;,&quot;education&quot;:&quot;Doctorate&quot;,&quot;householdsize&quot;:2,&quot;maritalstatus&quot;:&quot;M&quot;}]}<br>     .197802067 {&quot;customer_id&quot;:&quot;1272983&quot;,&quot;address&quot;:&quot; China China China&quot;,&quot;lifetime&quot;:10,&quot;profile&quot;:[{&quot;customer_id&quot;:1272983,&quot;gender&quot;:&quot;Male&quot;,&quot;education&quot;:&quot;Doctorate&quot;,&quot;householdsize&quot;:7,&quot;maritalstatus&quot;:&quot;M&quot;}]}<br>     .198005617 {&quot;customer_id&quot;:&quot;1282309&quot;,&quot;address&quot;:&quot; China China China&quot;,&quot;lifetime&quot;:6,&quot;profile&quot;:[{&quot;customer_id&quot;:1282309,&quot;gender&quot;:&quot;Male&quot;,&quot;education&quot;:&quot;Doctorate&quot;,&quot;householdsize&quot;:7,&quot;maritalstatus&quot;:&quot;M&quot;}]} <br>     .198038101 {&quot;customer_id&quot;:&quot;1357809&quot;,&quot;address&quot;:&quot; China China China&quot;,&quot;lifetime&quot;:5,&quot;profile&quot;:[{&quot;customer_id&quot;:1357809,&quot;gender&quot;:&quot;Male&quot;,&quot;education&quot;:&quot;Doctorate&quot;,&quot;householdsize&quot;:5,&quot;maritalstatus&quot;:&quot;M&quot;}]} <br>     .198122263 {&quot;customer_id&quot;:&quot;1409219&quot;,&quot;address&quot;:&quot; China China China&quot;,&quot;lifetime&quot;:3,&quot;profile&quot;:[{&quot;customer_id&quot;:1409219,&quot;gender&quot;:&quot;Male&quot;,&quot;education&quot;:&quot;Doctorate&quot;,&quot;householdsize&quot;:5,&quot;maritalstatus&quot;:&quot;M&quot;}]} <br>     .198339343 {&quot;customer_id&quot;:&quot;1112803&quot;,&quot;address&quot;:&quot; China China China&quot;,&quot;lifetime&quot;:4,&quot;profile&quot;:[{&quot;customer_id&quot;:1112803,&quot;gender&quot;:&quot;Male&quot;,&quot;education&quot;:&quot;Doctorate&quot;,&quot;householdsize&quot;:5,&quot;maritalstatus&quot;:&quot;M&quot;}]} <br>     .198434234 {&quot;customer_id&quot;:&quot;1421911&quot;,&quot;address&quot;:&quot; China China China&quot;,&quot;lifetime&quot;:8,&quot;profile&quot;:[{&quot;customer_id&quot;:1421911,&quot;gender&quot;:&quot;Male&quot;,&quot;education&quot;:&quot;Doctorate&quot;,&quot;householdsize&quot;:7,&quot;maritalstatus&quot;:&quot;M&quot;}]} <br>     .198506355 {&quot;customer_id&quot;:&quot;1427584&quot;,&quot;address&quot;:&quot; China China China&quot;,&quot;lifetime&quot;:4,&quot;profile&quot;:[{&quot;customer_id&quot;:1427584,&quot;gender&quot;:&quot;Male&quot;,&quot;education&quot;:&quot;Doctorate&quot;,&quot;householdsize&quot;:7,&quot;maritalstatus&quot;:&quot;M&quot;}]} <br>     .198592842 {&quot;customer_id&quot;:&quot;1248749&quot;,&quot;address&quot;:&quot; China China China&quot;,&quot;lifetime&quot;:11,&quot;profile&quot;:[{&quot;customer_id&quot;:1248749,&quot;gender&quot;:&quot;Male&quot;,&quot;education&quot;:&quot;Doctorate&quot;,&quot;householdsize&quot;:3,&quot;maritalstatus&quot;:&quot;S&quot;}]}<br>     .198690653 {&quot;customer_id&quot;:&quot;1338404&quot;,&quot;address&quot;:&quot; China China China&quot;,&quot;lifetime&quot;:20,&quot;profile&quot;:[{&quot;customer_id&quot;:1338404,&quot;gender&quot;:&quot;Male&quot;,&quot;education&quot;:&quot;Doctorate&quot;,&quot;householdsize&quot;:2,&quot;maritalstatus&quot;:&quot;M&quot;}]}<br>     .199161768 {&quot;customer_id&quot;:&quot;1268495&quot;,&quot;address&quot;:&quot; China China China&quot;,&quot;lifetime&quot;:4,&quot;profile&quot;:[{&quot;customer_id&quot;:1268495,&quot;gender&quot;:&quot;Male&quot;,&quot;education&quot;:&quot;Doctorate&quot;,&quot;householdsize&quot;:7,&quot;maritalstatus&quot;:&quot;M&quot;}]} <br>     .199282348 {&quot;customer_id&quot;:&quot;1240570&quot;,&quot;address&quot;:&quot; China China China&quot;,&quot;lifetime&quot;:11,&quot;profile&quot;:[{&quot;customer_id&quot;:1240570,&quot;gender&quot;:&quot;Male&quot;,&quot;education&quot;:&quot;Doctorate&quot;,&quot;householdsize&quot;:3,&quot;maritalstatus&quot;:&quot;S&quot;}]}<br>     .199346423 {&quot;customer_id&quot;:&quot;1398291&quot;,&quot;address&quot;:&quot; China China China&quot;,&quot;lifetime&quot;:1,&quot;profile&quot;:[{&quot;customer_id&quot;:1398291,&quot;gender&quot;:&quot;Male&quot;,&quot;education&quot;:&quot;Doctorate&quot;,&quot;householdsize&quot;:3,&quot;maritalstatus&quot;:&quot;S&quot;}]} <br>     .199405551 {&quot;customer_id&quot;:&quot;1107781&quot;,&quot;address&quot;:&quot; China China China&quot;,&quot;lifetime&quot;:11,&quot;profile&quot;:[{&quot;customer_id&quot;:1107781,&quot;gender&quot;:&quot;Male&quot;,&quot;education&quot;:&quot;Doctorate&quot;,&quot;householdsize&quot;:3,&quot;maritalstatus&quot;:&quot;S&quot;}]}<br><br>20 rows selected. <br><br>Elapsed: 00:00:12.078</pre><p>Even though there were 5,475 exact matches available, the vector search ranked customers with an identical address but not all other conditions as the most similar in the top 20 results. Therefore, I decided to run an additional test.</p><h4>Test 4</h4><p>I decided to leverage the Oracle Database converged capabilities applying a filter to remove from the customer base the customers with poor data quality in the address attribute.</p><pre><br>select vector_distance,<br>       customer_id,<br>       json_value(embed_data,<br>                  &#39;$.profile[0].gender&#39; returning varchar2(50)) gender,<br>       json_value(embed_data,<br>                  &#39;$.profile[0].education&#39; returning varchar2(50)) education,<br>       json_value(embed_data,<br>                  &#39;$.profile[0].householdsize&#39; returning varchar2(10)) householdsize,<br>       json_value(embed_data,<br>                  &#39;$.profile[0].maritalstatus&#39; returning varchar2(50)) maritalstatus,<br>       to_clob(embed_data) full_profile<br>  from (<br>   select ce.customer_id,<br>          ce.chunk_id,<br>          ce.embed_data,<br>          vector_distance(<br>             ce.embed_vector,<br>             (<br>                select to_vector(et.embed_vector) embed_vector<br>                  from dbms_vector_chain.utl_to_embeddings(<br>                   &#39;{&quot;gender&quot;:&quot;Male&quot;,&quot;education&quot;:&quot;Doctorate&quot;,&quot;maritalstatus&quot;:&quot;M&quot;}&#39;,<br>                   json(<br>                         &#39;{&quot;provider&quot;: &quot;OCIGenAI&quot;, <br>                            &quot;credential_name&quot;: &quot;OCI_GENAI_CRED&quot;, <br>                            &quot;url&quot;: &quot;https://inference.generativeai.us-chicago-1.oci.oraclecloud.com/20231130/actions/embedText&quot;, <br>                            &quot;model&quot;: &quot;cohere.embed-multilingual-v3.0&quot;}&#39;<br>                      )<br>                ) q,<br>                       json_table(q.column_value,<br>                          &#39;$[*]&#39;<br>                      columns(<br>                         embed_id number path &#39;$.embed_id&#39;,<br>                          embed_data varchar2(4000) path &#39;$.embed_data&#39;,<br>                          embed_vector clob path &#39;$.embed_vector&#39;<br>                      )<br>                   )<br>                et<br>             ),<br>             cosine<br>          ) as vector_distance<br>     from crm_customer_cv360embedding ce<br>    where json_value(ce.embed_data,<br>           &#39;$.address&#39;) not in ( &#39; China China China&#39;,<br>                                 &#39; Japan Japan Japan&#39;,<br>                                 &#39; Pakistan Pakistan Pakistan&#39;,<br>                                 &#39; Afghanistan Afghanistan Afghanistan&#39;,<br>                                 &#39; New Delhi Delhi India&#39; )<br>    order by vector_distance<br>    fetch first 20 rows only<br>);<br><br><br>VECTOR_DISTANCE CUSTOMER_ID GENDER                                             EDUCATION                                          HOUSEHOLDS MARITALSTATUS                                      FULL_PROFILE                                                                    <br>--------------- ----------- -------------------------------------------------- -------------------------------------------------- ---------- -------------------------------------------------- --------------------------------------------------------------------------------<br>2,022E-001          1320168 Male                                               Doctorate                                          2          M                                                  {&quot;customer_id&quot;:&quot;1320168&quot;,&quot;address&quot;:&quot; ঢাকা ঢাকা Bangladesh&quot;,&quot;lifetime&quot;:10,&quot;profil  <br>2,12E-001           1299819 Male                                               Doctorate                                          2          M                                                  {&quot;customer_id&quot;:&quot;1299819&quot;,&quot;address&quot;:&quot;הרצל תל אביב-יפו תל אביב Israel&quot;,&quot;lifetime&quot;:<br>2,126E-001          1425799 Male                                               Masters                                            2          M                                                  {&quot;customer_id&quot;:&quot;1425799&quot;,&quot;address&quot;:&quot; Dhaka Dhaka Bangladesh&quot;,&quot;lifetime&quot;:15,&quot;prof<br>2,132E-001          1302989 Male                                               Doctorate                                          7          M                                                  {&quot;customer_id&quot;:&quot;1302989&quot;,&quot;address&quot;:&quot; אשקלון דרום Israel&quot;,&quot;lifetime&quot;:8,&quot;profile&quot;:<br>2,134E-001          1004452 Male                                               Doctorate                                          1          S                                                  {&quot;customer_id&quot;:&quot;1004452&quot;,&quot;address&quot;:&quot; नई दिल्ली दिल्ली India&quot;,&quot;lifetime&quot;:6,&quot;profi    <br>2,139E-001          1292467 Male                                               Doctorate                                          1          S                                                  {&quot;customer_id&quot;:&quot;1292467&quot;,&quot;address&quot;:&quot; Dhaka Dhaka Bangladesh&quot;,&quot;lifetime&quot;:8,&quot;profi<br>2,144E-001          1298473 Male                                               Doctorate                                          1          S                                                  {&quot;customer_id&quot;:&quot;1298473&quot;,&quot;address&quot;:&quot; תל אביב תל אביב Israel&quot;,&quot;lifetime&quot;:2,&quot;profi<br>2,148E-001          1322787 Male                                               Masters                                            6          M                                                  {&quot;customer_id&quot;:&quot;1322787&quot;,&quot;address&quot;:&quot; ঢাকা ঢাকা Bangladesh&quot;,&quot;lifetime&quot;:7,&quot;profile  <br>2,152E-001          1319664 Male                                               Doctorate                                          3          S                                                  {&quot;customer_id&quot;:&quot;1319664&quot;,&quot;address&quot;:&quot; ঢাকা ঢাকা Bangladesh&quot;,&quot;lifetime&quot;:1,&quot;profile  <br>2,152E-001          1298489 Male                                               Doctorate                                          1          S                                                  {&quot;customer_id&quot;:&quot;1298489&quot;,&quot;address&quot;:&quot; תל אביב תל אביב Israel&quot;,&quot;lifetime&quot;:3,&quot;profi<br>2,162E-001          1120825 Male                                               Doctorate                                          1          S                                                  {&quot;customer_id&quot;:&quot;1120825&quot;,&quot;address&quot;:&quot; Japan 日本 Japan&quot;,&quot;lifetime&quot;:3,&quot;profile&quot;:[{&quot;c<br>2,164E-001          1301446 Male                                               Doctorate                                          2          M                                                  {&quot;customer_id&quot;:&quot;1301446&quot;,&quot;address&quot;:&quot;Μητροπόλεωσ Αθήνα Αττική Greece&quot;,&quot;lifetime&quot;:<br>2,164E-001          1077010 Male                                               Doctorate                                          2          M                                                  {&quot;customer_id&quot;:&quot;1077010&quot;,&quot;address&quot;:&quot;España Libertad Buenos Aires Argentina&quot;,&quot;lif<br>2,166E-001          1299441 Male                                               Doctorate                                          1          S                                                  {&quot;customer_id&quot;:&quot;1299441&quot;,&quot;address&quot;:&quot;יד חרוצים ירושלים ירושלים Israel&quot;,&quot;lifetime&quot;<br>2,167E-001          1119985 Male                                               Doctorate                                          2          M                                                  {&quot;customer_id&quot;:&quot;1119985&quot;,&quot;address&quot;:&quot; Japan 日本 Japan&quot;,&quot;lifetime&quot;:4,&quot;profile&quot;:[{&quot;c<br>2,169E-001          1128992 Male                                               Doctorate                                          7          M                                                  {&quot;customer_id&quot;:&quot;1128992&quot;,&quot;address&quot;:&quot; Japan 日本 Japan&quot;,&quot;lifetime&quot;:2,&quot;profile&quot;:[{&quot;c<br>2,173E-001          1012269 Male                                               Doctorate                                          7          M                                                  {&quot;customer_id&quot;:&quot;1012269&quot;,&quot;address&quot;:&quot; नई दिल्ली दिल्ली India&quot;,&quot;lifetime&quot;:2,&quot;profi    <br>2,176E-001          1132795 Male                                               Doctorate                                          1          S                                                  {&quot;customer_id&quot;:&quot;1132795&quot;,&quot;address&quot;:&quot; Japan 日本 Japan&quot;,&quot;lifetime&quot;:1,&quot;profile&quot;:[{&quot;c<br>2,18E-001           1348075 Male                                               Doctorate                                          2          M                                                  {&quot;customer_id&quot;:&quot;1348075&quot;,&quot;address&quot;:&quot; नई दिल्ली दिल्ली India&quot;,&quot;lifetime&quot;:3,&quot;profi    <br>2,18E-001           1291972 Male                                               Masters                                            1          S                                                  {&quot;customer_id&quot;:&quot;1291972&quot;,&quot;address&quot;:&quot; ঢাকা ঢাকা Bangladesh&quot;,&quot;lifetime&quot;:1,&quot;profile  <br><br>20 rows selected. <br><br>Elapsed: 00:00:03.807</pre><p>Notice how easy it was to combine traditional WHERE conditions with vector search conditions. Although I used JSON notation to apply the condition within the document, this highlights the advantage of having a converged database.</p><p>After cleaning the data, we found that 55% of the results with an exact match respect to the persona attributes specified in the prompt. So in this case my additional observation is that the current representation of marital status and household size, possibly due to encoding, may lack semantic clarity, which could be weakening its influence on the similarity score.</p><p>As outlined, the goal of this article was to showcase technological capabilities rather than validate the quality of the results, especially since no data quality tasks were performed to clean the original dataset. The examples above demonstrate how Oracle 23ai’s new features can provide an innovative approach to a common marketing challenge. In future work, I plan to explore this aspect further and investigate the use of hybrid search to achieve more granular control over lookalike searches.</p><h3>What unique advantages of OCI and Oracle 23ai</h3><p>Oracle Database 23ai is packed with innovation, so as we wrap up this initial journey of showcasing its potential, I’d like to recap the innovative and distinctive features we’ve explored.</p><ul><li><strong>Oracle 23ai Database Duality Views</strong> offer a significant advantage by enabling developers to seamlessly access and manipulate data in both relational and JSON formats within a single database. This eliminates the need to choose between these models and allows for a more flexible and efficient approach to data management. <strong>In essence, Duality Views bridge the gap between structured and semi-structured data, empowering developers to leverage the strengths of both worlds within a unified environment. </strong>Through this article, the duality view allows me to effortlessly generate a JSON document that delivers a 360-degree customer view, with no ETL, no data movement, and full preservation of real-time data change.</li><li>Oracle Database 23 now seamlessly integrates Generative AI with traditional data through its <strong>vector search capabilities</strong>, enabling unified data management that helps businesses unlock powerful insights and build innovative applications. I demonstrated how to leverage the vector store and vector search to perform semantic similarity, identifying similar customers based on their profiles. This was achieved again without the need for ETL processes or data movement, while also enabling combined searches that blend semantic search with traditional deterministic criteria. Beyond these benefits, I want to emphasize that embedding vector management within the Oracle Database also simplifies security, operations, scalability, and availability for enterprises.</li><li>The <strong>OCI GenAI service</strong> offers a <strong>fully managed suite of ready to use LLMs</strong> for tasks like embedding, generation, chat or summarization, which I utilized to transform JSON documents into vector embeddings. It can also be deployed on dedicated infrastructure, ensuring maximum security, optimized performance, and the capability to perform low-code LLM fine-tuning.</li></ul><p>Finally, the Oracle data platform provides a powerful tool for creating intuitive user interfaces to perform lookalike analysis and save segments using Oracle APEX. <strong>APEX is an incredibly powerful low-code platform for building applications</strong>, fully integrated with the Oracle database, especially within the Autonomous Database as fully managed tool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g2QZwHYn3kTakVy_yXFFJQ.png" /><figcaption>APEX UI example based on vector search capability</figcaption></figure><h3>Conclusion</h3><p>Thank you for reading! This article aimed to showcase the innovative capabilities of Oracle Database 23ai and the OCI GenAI service in addressing a common marketing challenge: identifying customer lookalikes through advanced AI techniques. By leveraging features such as JSON Relational Duality, native vector embeddings, and semantic search, Oracle 23ai provides a powerful framework to unlock new levels of precision and efficiency in customer segmentation and personalization. Whether you’re building a GenAI application from scratch or enhancing an existing solution, Oracle 23ai offers a robust and secure platform to drive innovation.</p><p>The code is intended for educational purposes and could certainly be improved. Comprehensive checks for a stable application have not been performed, and as such, no support is provided. I encourage you to test these features in your own use cases.</p><p>Enhancing data quality, integrating hybrid search techniques, building the UI by Oracle APEX, and applying these methods to dynamic, real-world scenarios are just a few areas for further investigation.</p><p><em>I hope this provides a fresh perspective on the use of Oracle 23ai database and OCI GenAI LLMs in the context of customer management. If you’d like, </em><a href="https://www.linkedin.com/in/michelemiscione/"><strong><em>follow</em></strong><em> </em><strong><em>me on Linkedin</em></strong><em>!</em></a></p><p><strong>References</strong></p><ul><li><a href="https://towardsdatascience.com/mastering-customer-segmentation-with-llm-3d9008235f41">Mastering Customer Segmentation with LLM</a></li><li><a href="https://www.griddynamics.com/blog/customer2vec-representation-learning-and-automl-for-customer-analytics-and-personalization">Customer2vec: Representation learning for customer analytics and personalization</a></li></ul><h3>Disclaimer</h3><p><em>The views expressed in this paper are my own and do not necessarily reflect the views of Oracle.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3d62d10fb17" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From JSON to Graph in a box]]></title>
            <link>https://medium.com/@michelemiscione/from-json-to-graph-in-a-box-aa9cb0866546?source=rss-51de94acaf95------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa9cb0866546</guid>
            <category><![CDATA[converged-database]]></category>
            <category><![CDATA[oracle]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[graph]]></category>
            <dc:creator><![CDATA[Michele Maria Miscione]]></dc:creator>
            <pubDate>Wed, 12 Jan 2022 13:29:41 GMT</pubDate>
            <atom:updated>2022-01-13T14:05:02.731Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>From JSON to Graph in a box (</strong>what does really mean Converged Database<strong>)</strong></h3><h3>Problem and Solution</h3><p>In the last months, I had the opportunity to work on a timetable optimization problem for one of my customers and I’d like to share the experience because is a good example of what does it really mean to work with the Oracle Converged Database leveraging the polyglot data model and the Oracle Autonomous Database on OCI and what are the related business and IT advantages.</p><p><strong>The Problem</strong></p><p>In the Travel &amp; Transportation industry, schedule definition and optimization is one of the biggest problems. Providing efficient algorithmic solutions to the problem of computing best journeys (or routes) in schedule-based public transportation systems imply the use of a flexible environment able to perform a different type of analysis on different model types. Some interesting articles explain the theory behind the problem such as <a href="https://www.sciencedirect.com/science/article/pii/S1570866717300606"><em>Engineering graph-based models for dynamic timetable information systems</em></a> or <a href="https://www.researchgate.net/publication/220243984_Modeling_and_Solving_the_Train_Timetabling_Problem"><em>Modeling and Solving the Train Timetabling Problem</em></a> but several of them investigated the Train Timetabling Problem (TTP) leveraging a graph model despite source information (time tables and routes) are in the systems in relational data model format and evolve in real-time often by API semi-structured data model (JSON or XML).</p><p>This data models heterogeneity was one of the main obstacles to achieving a flexible and business-oriented solution for the TTP complex problem with an efficient time to market.</p><p><strong>The Solution: Models and Approach</strong></p><p>Discovery, What-if analysis and Visualization were the key requirements to support the Time Table Definition especially about the coincidences analysis and definition based on the Minimum Connection Time (MCT). But the real challenge was to provide all these capabilities in a single and fully managed box for easy business user use and features consumption.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lUUo6cgWvVByT5nIq-vUUQ.png" /></figure><p><a href="https://www.oracle.com/autonomous-database/autonomous-data-warehouse/"><em>Oracle Autonomous Data Warehouse</em></a><em> (ADW) </em>with the embedded <a href="https://www.oracle.com/database/graph/graph-faq/"><em>Graph Studio</em></a> user interface plus spatial capabilities and user interface (Spatial Studio) is the easiest environment to reach a One Box solution that provides Relational, NoSql and Graph cross model analysis with what-if and prebuilt algorithm capabilities. This is the perfect fit for a business ready and fully managed <a href="https://www.oracle.com/data-lakehouse/">Data Lakehouse</a> environment to speed up business objectives.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sIJGP8aWZoT2xC8DicH_kQ.png" /></figure><p>So the solution was based on ADW on OCI where 1) data was accessed on the Object Storage via External Table, 2) raw data was enriched and prepared in the ADW leveraging views and Oracle Database Analytical &amp; Spatial functions without moving data, 3) a graph model was created in memory from the enriched non materialized view to enable the end-user analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lJOdK9EVrAglWvExfkwYbw.png" /></figure><p>The application was made only for educational purposes with some simplification to show multi-model Oracle converged database business benefits and time to market.</p><p>In the next part of the article there are the steps to replicate this lab articulated with the followed index:<br> 1) Load dataset from Kaggle to OCI Object Storage<br> 2) Access or load RAW JSON as a document on ADW from Object Storage<br> 3) Prepare &amp; enrich the data without persistence<br> 4) Create the in-memory Graph Data Model<br> 5) Create the notebook analysis for the train coincidence</p><h3><strong>LAB Experience</strong></h3><p>To build this application I performed the steps described below, if you want to replicate this example you need just to register on the <a href="https://www.oracle.com/cloud/free/"><em>Oracle Cloud Free Tier</em></a><em> </em>and create the Object Storage bucket and the ADW before starting with the next steps described in the article. You can read from <a href="https://luca-bindi.medium.com/create-an-apex-application-using-collection-json-relationa-data-spatial-data-and-blockchain-a87429212a89"><em>this Luca Bindi’s article</em></a> how to create the ADW and the Object Storage bucket looking at the paragraphs “Create Autonomous Database” and “Load The {JSON} Document”. This is a really useful article to read and another good example about the converged database benefits.</p><ol><li><strong>Load dataset in the OCI Object Storage</strong></li></ol><p>To simulate the problem solution approach with real-world data I always look at <a href="https://www.kaggle.com/datasets"><em>Kaggle Datasets</em></a><em> </em>and even this time I was able to find what I needed, the <a href="https://www.kaggle.com/sripaadsrinivasan/indian-railways-dataset"><em>Indian Railways Dataset</em></a> from <a href="https://www.kaggle.com/sripaadsrinivasan"><em>Sripaad Srinivasan</em></a> with JSON files format. To make the Kaggle JSON files available for the ADW it is possible to manually load the files on the bucket from the OCI Console or use the Command Line Interface (CLI). See <a href="https://docs.oracle.com/en-us/iaas/tools/oci-cli/3.4.1/oci_cli_docs/">Oracle Cloud Infrastructure CLI Command Reference</a> for more details about how to install and configure CLI on your laptop. Now I’m showing the use of CLI because the manual procedure is really simple.</p><p>1.1. Create the Object Storage bucket</p><pre>oci os bucket create -ns &lt;mynamespace&gt; —-compartment-id &lt;compartment&gt; --name graphlab</pre><p>1.2. Load file to the Object Storage bucket</p><pre>oci os object bulk-upload -ns &lt;mynamespace&gt; -bn graphlab --src-dir path/to/upload/directory</pre><p>Please consider that I added the suffix “pi_” to my file during the LAB so in the next steps you will see this suffix in from to my file name in some screenshots.</p><p><strong>2. Access or load RAW JSON as a document on ADW from Object Storage</strong></p><p>Open the SQL Developer Web ADW Tool from the OCI console following the path in the console: Autonomous Database instance -&gt; Database Actions -&gt; Development -&gt; SQL</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qbsaeu0lJMF2VanPYgWcIQ.png" /></figure><p>2.1. Create a credential store to access the bucket from ADW</p><p>To create a credential store it is needed to create an authorization token. On the OCI Console from Identity&gt;Users&gt;User Details&gt;Auth Tokens click on “Generate Token” and save it on your laptop by clicking on the button “Copy”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lNOaN81Ux11JNiDtUJTPFg.png" /></figure><p>Then from the SQL Developer Web ADW Tool execute the following code:</p><pre>BEGIN<br>DBMS_CLOUD.CREATE_CREDENTIAL(<br>credential_name =&gt; ‘OBJ_STORE_GRAPH_LAB_EXTT’,<br>username =&gt; ‘Your User’,<br>password =&gt; ‘User Auth Token Here’<br>);<br>END;<br>/</pre><p>2.2. Create the External Tables to access the JSON files from the ADW</p><p>Test the access to the bucket with the created credentials using the path of the bucket you created (you can keep the path from Object Storage&gt;Bucket Details and then click on the right menu on one file in the bucket and select “View Object Detail”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GDNDZ340QSmMUbNVVDJEhA.png" /></figure><p>Then execute this code in the SQL Developer Web ADW Tool:</p><pre>select *<br>from dbms_cloud.list_objects(&#39;OBJ_STORE_GRAPH_LAB_EXTT&#39;,&#39;<a href="https://objectstorage.eu-frankfurt-1.oraclecloud.com/n/emeaseitalysandbox/b/pianificazione_industriale/o&#39;">Your Path&#39;</a>)<br>;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uwCqlbQJ2FXrWwxS5i97aA.png" /></figure><p>Now we can create the external table to access remotely on the Object Storage the JSON file executing:</p><pre>DROP table EXT_COLL_STATION purge;</pre><pre>BEGIN<br>DBMS_CLOUD.CREATE_EXTERNAL_TABLE(<br>table_name =&gt;&#39;EXT_COLL_STATION&#39;,<br>credential_name =&gt;&#39;OBJ_STORE_GRAPH_LAB_EXTT&#39;,<br>file_uri_list =&gt;&#39;Your Path/stations.json&#39;,<br>format =&gt; json_object(&#39;recorddelimiter&#39; value &#39;newline&#39;,&#39;maxdocsize&#39; value 104857600, &#39;rejectlimit&#39; value 10000000 , &#39;unpackarrays&#39; value TRUE ),<br>column_list =&gt; &#39;json_document blob&#39;,<br>field_list =&gt; &#39;json_document char(5000000000)&#39;<br>);<br>END;<br>/</pre><pre>BEGIN<br>DBMS_CLOUD.VALIDATE_EXTERNAL_TABLE(<br>table_name =&gt; &#39;EXT_COLL_STATION&#39;,<br>schema_name =&gt; &#39;MMISCIONE&#39;<br>);<br>END;<br>/</pre><p>Now we can query from ADW the JSON file on the Object Storage bucket using the <a href="https://docs.oracle.com/en/database/oracle/oracle-database/21/adjsn/simple-dot-notation-access-to-json-data.html#GUID-7249417B-A337-4854-8040-192D5CEFD576">Dot-Notation</a>:</p><pre>SELECT json_value(json_document, &#39;$.features[1].properties.code&#39; RETURNING CLOB ERROR ON ERROR) AS STATION_CODE FROM mmiscione.EXT_COLL_STATION;</pre><pre>STATION_CODE <br>------------ <br>XX-BECE      <br><br>Elapsed: 00:00:00.405<br>1 rows selected.</pre><pre>SELECT<br>JSON_VALUE(json_document, &#39;$.type&#39;)                                       AS type,<br>json_query(json_document, &#39;$.features&#39; RETURNING clob WITH ARRAY WRAPPER) AS features<br>FROM mmiscione.ext_coll_station<br>WHERE json_document IS JSON;</pre><pre>TYPE              FEATURES<br>----------------- -------------------------------------<br>FeatureCollection [[{&quot;geometry&quot;:{&quot;type&quot;:&quot;Point&quot;,&quot;coo...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WyAY0M38OxoCYRcYKt0ooQ.png" /></figure><p>You need to repeat these steps for all the files: pi_schedules.json, pi_stations.json, pi_trains.json. This enables you to access the data on the object storage without moving it on the database but it is also possible to load the file into the ADW as document collection as Luca Bindi described <a href="https://luca-bindi.medium.com/create-an-apex-application-using-collection-json-relationa-data-spatial-data-and-blockchain-a87429212a89">here</a> using the DBMS_CLOUD.COPY_COLLECTION. Just for example, you can use the following code to load the JSON file from the bucket to the database as a document.</p><pre>BEGIN<br>DBMS_CLOUD.COPY_COLLECTION(<br>collection_name =&gt; &#39;stg_coll_station&#39;,<br>credential_name =&gt; &#39;OBJ_STORE_GRAPH_LAB_EXTT&#39;,<br>file_uri_list =&gt; &#39;Your Path/stations.json<a href="https://objectstorage.eu-frankfurt-1.oraclecloud.com/p/in2tAmqSvbWp8-vGmmf9HWw-samUQ6i5O63CSfYCg15istw_uTdZjh31X3Lqx1Rl/n/emeaseitalysandbox/b/pianificazione_industriale/o/pi_stations.json&#39;">&#39;</a>,<br>format =&gt; json_object(&#39;recorddelimiter&#39; value &#39;newline&#39;,&#39;maxdocsize&#39; value 104857600, &#39;rejectlimit&#39; value 10000000 , &#39;unpackarrays&#39; value TRUE )<br>);<br>END;<br>/</pre><p>You can use the same json_value or json_query posted before for the external table on the documents collection table to query the JSON by Dot Notation.</p><p><strong>3. Prepare &amp; enrich the data on the fly (without persistence)</strong></p><p>Now that we can access the JSON data either if on the Object Storage JSON files via External Table or on the database as a document by the data copy the data preparation can start. To maximize the flexibility I decided to use a view on the external table to keep any kind of change on the original file on the bucket. This is an option but several others are feasible in case of data persistence on the database.</p><p>Data preparation consists of three types of manipulations:<br>*) Prepare the data to fuel the Graph Model (we will need two tables one for the vertices and one for the edges). To have the edges I need to manipulate the pi_schedules.json data with a LEAD analytic function to have origin and destination vertex on the same line.<br>*) Add calculated KPI such as the duration or the distance<br>*) Remove dirty data about stations, trains or schedules with consistency.</p><p>So first I created two basic views to extract with schema on read approach only the relevant information for stations and schedules.</p><pre>CREATE OR REPLACE VIEW VW_STATIONS AS<br>SELECT<br>T.&quot;STATIONS_CODE&quot;,<br>T.&quot;STATIONS_ADDRESS&quot;,<br>T.&quot;STATIONS_NAME&quot;,<br>T.&quot;STATIONS_LON&quot;,<br>T.&quot;STATIONS_LAT&quot;<br>FROM<br>MMISCIONE.EXT_COLL_STATION,<br>JSON_TABLE ( JSON_DOCUMENT, &#39;$.features[*]&#39;<br>COLUMNS (<br>STATIONS_CODE VARCHAR2 ( 10 ) PATH &#39;$.properties.code&#39;,<br>STATIONS_ADDRESS VARCHAR2 ( 2000 ) PATH &#39;$.properties.address&#39;,<br>STATIONS_NAME VARCHAR2 ( 100 ) PATH &#39;$.properties.name&#39;,<br>STATIONS_LON NUMBER PATH &#39;$.geometry.coordinates[0]&#39;,<br>STATIONS_LAT NUMBER PATH &#39;$.geometry.coordinates[1]&#39;<br>)<br>)<br>AS T<br>WHERE<br>T.STATIONS_CODE IS NOT NULL<br>AND T.STATIONS_NAME IS NOT NULL;</pre><pre>CREATE OR REPLACE VIEW VW_SCHEDULES AS<br>SELECT<br>T.&quot;ID&quot;,<br>T.&quot;TRAIN_NUMBER&quot;,<br>T.&quot;TRAIN_NAME&quot;,<br>T.&quot;STATION_NAME&quot;,<br>T.&quot;STATION_CODE&quot;,<br>T.&quot;ARRIVAL&quot;,<br>T.&quot;DAY&quot;,<br>T.&quot;DEPARTURE&quot;<br>FROM EXT_COLL_SCHEDULES,<br>JSON_TABLE ( JSON_DOCUMENT, &#39;$[*]&#39;<br>COLUMNS (<br>ID NUMBER PATH &#39;$.id&#39;,<br>TRAIN_NUMBER NUMBER PATH &#39;$.train_number&#39;,<br>TRAIN_NAME VARCHAR2 ( 1000 ) PATH &#39;$.train_name&#39;,<br>STATION_NAME VARCHAR2 ( 1000 ) PATH &#39;$.station_name&#39;,<br>STATION_CODE VARCHAR2 ( 10 ) PATH &#39;$.station_code&#39;,<br>ARRIVAL VARCHAR2 ( 10 ) PATH &#39;$.arrival&#39;,<br>DAY NUMBER PATH &#39;$.day&#39;,<br>DEPARTURE VARCHAR2 ( 10 ) PATH &#39;$.departure&#39;<br>)<br>)<br>AS T<br>WHERE<br>T.&quot;DAY&quot; IS NOT NULL<br>AND T.&quot;STATION_CODE&quot; &lt;&gt; &#39;P&#39;;</pre><p>Now I did the enrichment of the schedules data to prepare the edges for the graph model. Several operations were done:</p><ol><li>the internal subselect aim is to have on the same line the destination information by the use of LEAD Analytical Function.</li><li>the external where conditions aim is to filter final destination information because already available by the previous step with the final-1 hop and filter inconsistent data with STATION_CODE=0 or hop duration less than zero.</li><li>the output was enriched with some calculations related to departure and arrival timestamp in date format and duration because of some inconsistency in the original dataset.</li></ol><pre>CREATE OR REPLACE VIEW VW_HOPS AS<br>    SELECT<br>        ID,<br>        TRAIN_NUMBER,<br>        TRAIN_NAME,<br>        DAY,<br>        DEPARTURE,<br>        TO_DATE(DEPARTURE, &#39;HH24:MI:SS&#39;) + DAY - 1                                                         DEPARTURE_DATE,<br>        ( TO_DATE(DEPARTURE, &#39;HH24:MI:SS&#39;) + DAY - 1 - TO_DATE(&#39;00:00:00&#39;, &#39;HH24:MI:SS&#39;) ) * 24 * 60       DEP_MINUTES,<br>        STATION_CODE,<br>        STATION_NAME,<br>        NEW_ARRIVAL,<br>        NEW_DAY,<br>        TO_DATE(NEW_ARRIVAL, &#39;HH24:MI:SS&#39;) + NEW_DAY - 1                                                   NEW_ARRIVAL_DATE,<br>        ( TO_DATE(NEW_ARRIVAL, &#39;HH24:MI:SS&#39;) + NEW_DAY - 1 - TO_DATE(&#39;00:00:00&#39;, &#39;HH24:MI:SS&#39;) ) * 24 * 60 ARR_MINUTES,<br>        STATION_ARRIVAL_CODE,<br>        STATION_ARRIVAL_NAME,<br>        CASE<br>            WHEN ( ( ( TO_DATE(NEW_ARRIVAL, &#39;HH24:MI:SS&#39;) + NEW_DAY - 1 - TO_DATE(&#39;00:00:00&#39;, &#39;HH24:MI:SS&#39;) ) * 24 * 60 - ( TO_DATE(DEPARTURE,<br>            &#39;HH24:MI:SS&#39;) + DAY - 1 - TO_DATE(&#39;00:00:00&#39;, &#39;HH24:MI:SS&#39;) ) * 24 * 60 ) * 60 ) = 0 THEN<br>                0.1<br>            ELSE<br>                ( ( ( TO_DATE(NEW_ARRIVAL, &#39;HH24:MI:SS&#39;) + NEW_DAY - 1 - TO_DATE(&#39;00:00:00&#39;, &#39;HH24:MI:SS&#39;) ) * 24 * 60 - ( TO_DATE(DEPARTURE,<br>                &#39;HH24:MI:SS&#39;) + DAY - 1 - TO_DATE(&#39;00:00:00&#39;, &#39;HH24:MI:SS&#39;) ) * 24 * 60 ) * 60 )<br>        END                                                                                                DURATION_SEC<br>    FROM<br>        (<br>            SELECT<br>                ID,<br>                TRAIN_NUMBER,<br>                TRAIN_NAME,<br>                DAY,<br>                DEPARTURE,<br>                STATION_CODE,<br>                STATION_NAME,<br>                NEW_ARRIVAL,<br>                NEW_DAY,<br>                STATION_ARRIVAL_CODE,<br>                STATION_ARRIVAL_NAME<br>            FROM<br>                (<br>                    SELECT<br>                        ID,<br>                        TRAIN_NUMBER,<br>                        TRAIN_NAME,<br>                        DAY,<br>                        DEPARTURE,<br>                        STATION_CODE,<br>                        STATION_NAME,<br>                        CASE<br>                            WHEN LEAD(ARRIVAL, 1, 0)<br>                                 OVER(PARTITION BY TRAIN_NUMBER<br>                                      ORDER BY<br>                                          ID<br>                                 ) IN ( &#39;0&#39;, &#39;None&#39; ) THEN<br>                                DEPARTURE<br>                            ELSE<br>                                LEAD(ARRIVAL, 1, 0)<br>                                OVER(PARTITION BY TRAIN_NUMBER<br>                                     ORDER BY<br>                                         ID<br>                                )<br>                        END NEW_ARRIVAL,<br>                        CASE<br>                            WHEN LEAD(DAY, 1, 0)<br>                                 OVER(PARTITION BY TRAIN_NUMBER<br>                                      ORDER BY<br>                                          ID<br>                                 ) = 0 THEN<br>                                DAY<br>                            ELSE<br>                                LEAD(DAY, 1, 0)<br>                                OVER(PARTITION BY TRAIN_NUMBER<br>                                     ORDER BY<br>                                         ID<br>                                )<br>                        END NEW_DAY,<br>                        LEAD(STATION_CODE, 1, 0)<br>                        OVER(PARTITION BY TRAIN_NUMBER<br>                             ORDER BY<br>                                 ID<br>                        )   STATION_ARRIVAL_CODE,<br>                        LEAD(STATION_NAME, 1, 0)<br>                        OVER(PARTITION BY TRAIN_NUMBER<br>                             ORDER BY<br>                                 ID<br>                        )   STATION_ARRIVAL_NAME<br>                    FROM<br>                        MMISCIONE.VW_SCHEDULES<br>                    WHERE<br>                        DEPARTURE &lt;&gt; &#39;None&#39;<br>                    ORDER BY<br>                        ID ASC<br>                )<br>        )<br>    WHERE<br>            NEW_ARRIVAL &lt;&gt; &#39;0&#39;<br>        AND STATION_ARRIVAL_CODE &lt;&gt; &#39;0&#39;<br>        AND ( TO_DATE(NEW_ARRIVAL, &#39;HH24:MI:SS&#39;) + NEW_DAY - 1 - TO_DATE(&#39;00:00:00&#39;, &#39;HH24:MI:SS&#39;) ) * 24 * 60 - ( TO_DATE(DEPARTURE,<br>        &#39;HH24:MI:SS&#39;) + DAY - 1 - TO_DATE(&#39;00:00:00&#39;, &#39;HH24:MI:SS&#39;) ) * 24 * 60 &gt;= 0;</pre><p><strong>4. Create the in-memory Graph Data Model</strong></p><p>As described at the beginning of the article to create a property graph we need two main structures: vertices and edges. Based on the scientific literature we could have a complex property graph for the Train Timetabling Problem (TTP) but to simplify in this lab we will have the mapping:<br> * Vertices = Stations &gt; VW_STATIONS<br> * Edges = Schedules enriched &gt; VW_HOPS</p><p>But also we could have different ways to create the property graph on the Oracle database. Based on the same criteria used before, to keep maximum flexibility I decided to not persist the graph and create it in memory from the view. To do it I need to enable the creation of the property graph on the view.</p><pre>CREATE TABLE graph.ADB_GRAPH_SETTINGS$ (<br>  key VARCHAR2(255) primary key,<br>  value VARCHAR2(255) NOT NULL<br>);<br>INSERT INTO graph.ADB_GRAPH_SETTINGS$ VALUES (&#39;PG_VIEWS_ENABLED&#39;, &#39;true&#39;);<br>COMMIT;</pre><p>Keep in mind that in this case it needs to manually verify the foreign key constraint because all the vertices source and target must be declared as a vertiex.</p><p>Now from the Autonomous Database instance &gt; Tools &gt; Graph Studio it is possible to create the property graph. Select on the left side menu the Graphs tab and click on Create button on the top right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TdkueDGI4Doa2omLw34LIg.png" /></figure><p>Select “Graph Type = PG View” and the views related to the vertices and edges on the left side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hoHCJuLdtlmHMRmZxan0kA.png" /></figure><p>Then clicking on next we have to put the property graph creation code. In case of use of tables with primary and foreign keys declared this step will be optional because of auto-generated code. In this case Graph Studio is not able to identify primary and foreign keys due to the choice to start from dynamic views.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3y-nS3W7Xq2lBCIv7l627w.png" /></figure><p>So we have to replace the code with the following:</p><pre>CREATE PROPERTY GRAPH TRAIN_SCHEDULE_GRAPH<br>  VERTEX TABLES (<br>    mmiscione.vw_stations as station<br>      KEY ( stations_code )<br>      PROPERTIES ( stations_address, stations_code, stations_lat, stations_lon, stations_name )<br>  )<br>  EDGE TABLES (<br>    mmiscione.vw_hops as connection<br>      KEY ( id )<br>      SOURCE KEY ( station_code ) REFERENCES station<br>      DESTINATION KEY ( station_arrival_code ) REFERENCES station<br>      PROPERTIES ( arr_minutes, day, new_day, departure, departure_date, dep_minutes, duration_sec, id, new_arrival, new_arrival_date, station_arrival_code, station_arrival_name, station_code, station_name, train_name, train_number )<br>  )</pre><p>Then click save and next. The property graph will be created and loaded into the memory. So you have now the graph ready for analysis. Because we decided to not persist any step of the data preparation by in-memory graph unload and load from the Graph tab in the left side menu we can have any change on the object storage file just with two clicks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M_A2Of50MMhckMfhARwX-g.png" /></figure><p><strong>5. Create the notebook analysis for the train coincidence</strong></p><p>Now it is possible to create a notebook to make the analysis so click on Notebooks on the left side menu e the on create.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*urK2fBiw3Ez8QRCyq-pt1w.png" /></figure><p>On the notebook it is possible to use pgql-pgx, java-pgx or python-pgx to interact with the graph via <a href="https://pgql-lang.org/">PGQL</a> that is a graph query language built on top of SQL, bringing graph pattern matching capabilities to existing SQL users as well as to new users who are interested in graph technology but who do not have an SQL background, or <a href="https://docs.oracle.com/cd/E56133_01/latest/reference/analytics/builtins.html">executing the prebuilt algorithm</a>.</p><p><strong>5.1. Just some examples of analysis</strong></p><p>To show the stations with the highest number of connections (edges for our graph model) comparing the number or feasible coincidences based on the time interval of feasibility e.g. min 10 minutes and max 30 minutes we can use the PGX query</p><pre>SELECT s.STATIONS_CODE as STATION_CODE, <br>       s.STATIONS_NAME as STATION_NAME, <br>       max(in_degree(s) + out_degree(s)) as max_num_arr_dep,<br>       avg(b.DEP_MINUTES - a.ARR_MINUTES) as avg_conn_time,<br>       count(a.TRAIN_NUMBER + b.TRAIN_NUMBER) as num_trains<br>FROM MATCH () -[a]-&gt; (s) -[b]-&gt;() ON TRAIN_SCHEDULE_V5<br>where a.STATION_CODE != b.STATION_ARRIVAL_CODE<br>  and b.DEP_MINUTES - a.ARR_MINUTES &gt; ${min_time}<br>  and b.DEP_MINUTES - a.ARR_MINUTES &lt; ${min_time}+${delta}<br>group by s.STATIONS_CODE, s.STATIONS_NAME<br>order by max_num_arr_dep desc<br>limit 100</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2FrB-0oYQcTn9qXPQZprtw.png" /></figure><p>Or if you want to calculate the Shortest Path using Dijkstra from two stations you can use this simple PGX query</p><pre>SELECT distinct a.STATIONS_CODE as origin,<br>       LISTAGG(distinct e.train_number, &#39; , &#39;) as train_hops, <br>       count(distinct e.train_number) as num_cambi,<br>       LISTAGG(distinct e.STATION_CODE, &#39; , &#39;) as station_hops,<br>       b.STATIONS_CODE as destin,<br>       LISTAGG(e.DURATION_SEC, &#39; , &#39;) as duration_sequence, <br>       SUM(e.DURATION_SEC)/60 AS tot_duration_min<br>  FROM MATCH TOP 3 SHORTEST (a:station) - [e:connection] -&gt;* (b:station) ON TRAIN_SCHEDULE_GRAPH<br> WHERE a.stations_code = &#39;${station_to=PRGD}&#39;  AND b.stations_code =  &#39;${station_HUB= KOTR,KOTR|GWYR|TYMR|INDR|BRST|KTBR|MACR|JRPD}&#39;<br> ORDER BY tot_duration_min</pre><p>Or for the cheapest path</p><pre>SELECT a.STATIONS_CODE as origin,<br>       b.STATIONS_CODE as destin,<br>       SUM(e.DURATION_SEC)/60 AS tot_dur_min, <br>       count(distinct e.train_number) as num_cambi,<br>       LISTAGG(distinct e.train_number, &#39; + &#39;) as train_hops,<br>       LISTAGG(distinct e.STATION_CODE, &#39; , &#39;) as station_hops,<br>       SUM(e.DURATION_SEC) AS tot_duration, <br>       LISTAGG(e.DURATION_SEC, &#39; , &#39;) as duration_sequence <br>  FROM MATCH CHEAPEST ( (a:station) (-[e:connection]-&gt; COST e.DURATION_SEC)* (b:station) ) ON TRAIN_SCHEDULE_V5<br> WHERE a.stations_code = &#39;${station_to=PRGD,PRGD}&#39; AND b.stations_code = &#39;${station_HUB= KOTR,KOTR|GWYR|TYMR|INDR|KTBR|BRST|KTBR|MACR}&#39;<br> ORDER BY tot_duration</pre><p>In addition, to enable what-if and modify the schedule to find the best timetable solution it is also possible to <a href="https://pgql-lang.org/spec/1.4/#graph-modification">easily modify the graph in memory by PGQL</a>.</p><p><strong>5.2. The Graph Studio notebook</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RujVsUJNryVGPf4u4VEibQ.png" /></figure><p><a href="https://youtu.be/ftTSV8Kwos8">Here you can see</a> what it is possible to create in Spatial Studio to analyse the graph, also in this case is just a simple example to show high-level capabilities. Special Studio is an Autonomous Database embedded tool available in OCI Console&gt;Autonomous Database Instance&gt;Tools.</p><p>This is just an example of what kind of simplification can provide the use of Oracle Converged Database, especially if with Autonomous Cloud Service. Main business value comes from:</p><ol><li><strong>Fast Modelling</strong><br>no ETL but direct access to the RAW data with schema on read</li><li><strong>Agile Approach</strong><br>from persist and replace to on the fly, in-memory fast fail approach in a fully managed and secure environment</li><li><strong>Native Model and Cross Model easy Analysis</strong><br>graph pattern matching, analytical function, key-value query for each specific need and combined easily together in one box</li></ol><p>I hope this can be useful, <a href="https://www.linkedin.com/in/michelemiscione/">contact me</a> for further information.</p><p><a href="https://github.com/mmmiscione/OADW-json2graph">GitHub - mmmiscione/OADW-json2graph</a></p><h3>Disclaimer</h3><p><em>The views expressed in this paper are my own and do not necessarily reflect the views of Oracle.</em></p><h3>Acknowledgement and useful links</h3><p>If you are interested in the Oracle Converged Database capabilities and or specifically on the Oracle Graph features you can follow <a href="https://luca-bindi.medium.com/">Luca Bindi</a>, <a href="https://www.linkedin.com/in/fabrizio-orlando-3086712/">Fabrizio Orlando</a> and <a href="https://www.linkedin.com/in/agodfrind/">Albert Godfrind</a> that collaborated with me on this lab and which I would like to thank for your cooperation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa9cb0866546" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>