<?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 Karthikn on Medium]]></title>
        <description><![CDATA[Stories by Karthikn on Medium]]></description>
        <link>https://medium.com/@karthikn.js?source=rss-9f0aa679b51e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VSgbR_toH7SGx7NkPzOeeQ.jpeg</url>
            <title>Stories by Karthikn on Medium</title>
            <link>https://medium.com/@karthikn.js?source=rss-9f0aa679b51e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 14:50:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@karthikn.js/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[Linux Essentials commands for SRE, DevOps, and Cloud Engineers]]></title>
            <link>https://medium.com/@karthikn.js/linux-essentials-commands-222e85272c1d?source=rss-9f0aa679b51e------2</link>
            <guid isPermaLink="false">https://medium.com/p/222e85272c1d</guid>
            <dc:creator><![CDATA[Karthikn]]></dc:creator>
            <pubDate>Wed, 21 Jan 2026 05:07:17 GMT</pubDate>
            <atom:updated>2026-04-16T02:13:24.385Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>tr — </strong>used to transform, delete, or &quot;squeeze&quot; characters from standard input and write the result to standard output.</p><pre>Syntax:<br>  tr [options] SET1 [SET2]<br><br>  SET1: The characters you want to find.<br>  SET2: The characters you want to use as replacements<br><br>Change Case (Lower to Upper):<br>echo &quot;hello linux&quot; | tr &#39;a-z&#39; &#39;A-Z&#39;<br># Output: HELLO LINUX<br><br>Delete Characters (-d)<br>echo &quot;Phone: 123-456-7890&quot; | tr -d &#39;-&#39;<br># Output: Phone: 1234567890<br><br>Squeeze Repeats (-s)<br>echo &quot;Too    many    spaces&quot; | tr -s &#39; &#39;<br># Output: Too many spaces<br><br>Keep Only Specific Characters [-c (complement and -d]<br>echo &quot;User ID: 90210&quot; | tr -cd &#39;[:digit:]&#39;<br># Output: 90210<br><br>Replace Characters<br>echo &quot;file name with spaces&quot; | tr &#39; &#39; &#39;_&#39;<br># Output: file_name_with_spaces</pre><p><strong>sed — </strong>perform basic text transformations, such as searching, replacing, inserting, and deleting, on an input stream or file.</p><pre>Syntax:<br>    sed [options] &#39;script&#39; file<br><br>Create a sample file:<br><br>echo -e &quot;1:Small house:Vermont:100 sqm\n2:Large house:San Diego:300 sqm\n3:Apartment:New York:70 sqm\n4:Houseboat:London:40 sqm&quot; &gt; houses.txt<br><br>Example 1: Insert Text Before a Line<br><br>sed &#39;1i\<br>quote&gt; 0:Medium house:San Jose:350 sqm<br>quote&gt; &#39; houses.txt<br><br>0:Medium house:San Jose:350 sqm<br>1:Small house:Vermont:100 sqm<br>2:Large house:San Diego:300 sqm<br>3:Apartment:New York:70 sqm<br>4:Houseboat:London:40 sqm<br><br>Example 2: Append Text After a Line<br><br>sed &#39;4a\<br>quote&gt; 5:Medium house:San Jose:350 sqm<br>quote&gt; &#39; houses.txt<br><br>1:Small house:Vermont:100 sqm<br>2:Large house:San Diego:300 sqm<br>3:Apartment:New York:70 sqm<br>4:Houseboat:London:40 sqm<br>5:Medium house:San Jose:350 sqm<br><br>Example 3: Search and replace - globally and ignore case<br><br>sed &#39;s/new/old/gi&#39; houses.txt <br><br>1:Small house:Vermont:100 sqm<br>2:Large house:San Diego:300 sqm<br>3:Apartment:old York:70 sqm<br>4:Houseboat:London:40 sqm<br><br>Example 4:Extract Lines Between Patterns<br><br>sed -n &#39;/2/,/4/p&#39; houses.txt<br><br>2:Large house:San Diego:300 sqm<br>3:Apartment:New York:70 sqm<br>4:Houseboat:London:40 sqm<br><br>Example 5:Delete specific Lines <br><br>sed &#39;2d&#39; houses.txt <br><br>1:Small house:Vermont:100 sqm<br>3:Apartment:New York:70 sqm<br>4:Houseboat:London:40 sqm<br><br>Example 6:Delete Lines Matching a Pattern<br><br>sed &#39;/Houseboat/d&#39; houses.txt<br><br>1:Small house:Vermont:100 sqm<br>2:Large house:San Diego:300 sqm<br>3:Apartment:New York:70 sqm</pre><p><strong>awk</strong>—text processing utility used for manipulating and analyzing text files.</p><ul><li>pattern: A regular expression or a conditional statement that determines <strong>which lines to process</strong>.</li><li>action: The commands to be executed <strong>on the lines that match the </strong><strong>pattern</strong>. Actions are enclosed in curly braces {}.</li><li>input_file: The file to be processed by the awk command. If no file is specified, itawk reads from standard input</li></ul><pre>Syntax: <br>    awk &#39;BEGIN {Preprocessing} pattern { action } END {Postprocessing}&#39;<br><br>Create a sample file:<br>echo -e &quot;1:Small house:Vermont:100 sqm\n2:Large house:San Diego:300 sqm\n3:Apartment:New York:70 sqm\n4:Houseboat:London:40 sqm&quot; &gt; houses.txt<br><br>Example 1: Printing fields<br><br>awk -F &#39;:&#39; &#39;<br>  BEGIN { print &quot;HouseNo. &quot; &quot; HouseType &quot; &quot; HouseName &quot; &quot; HouseSize&quot; } <br>  { print $1 &quot;\t&quot; $2 &quot;\t&quot; $3  &quot;\t&quot; $4 } <br>  END { print &quot;No more houses Thanks&quot; }<br>&#39; houses.txt<br><br>HouseNo.  HouseType  HouseName  HouseSize<br>1 Small house Vermont 100 sqm<br>2 Large house San Diego 300 sqm<br>3 Apartment New York 70 sqm<br>4 Houseboat London 40 sqm<br>No more houses Thanks<br><br>Example 2: Mathematical Operation<br><br>awk -F &#39;:&#39; &#39; <br>  BEGIN {print &quot;Sum of sqm&quot;} <br>  { print $4 ; sum = sum + $4+0 } <br>  END {print &quot;Total &quot;, sum} &#39; houses.txt <br><br>Sum of sqm<br>100 sqm<br>300 sqm<br>70 sqm<br>40 sqm<br>Total  510<br><br>Example 3: Conditional<br><br>awk -F &#39;:&#39; &#39; <br>  BEGIN { print &quot;House sqm &gt; 100&quot; } <br>  { if ($4+0 &gt; 100) print $3 } <br>  &#39; houses.txt<br><br>House sqm &gt; 100<br>San Diego<br><br>Example 4: Pattern search<br>awk -F &quot;:&quot; &#39;<br>  /Vermont/ {print $0}<br>  &#39; houses.txt <br><br>1:Small house:Vermont:100 sqm<br><br>Example 5: Using built-in functions <br><br>awk -F &#39;:&#39; &#39;<br>  {<br>    gsub(/house/, &quot;mansion&quot;, $2);  <br>    print tolower($2)<br>  }<br>&#39; houses.txt<br><br>small mansion<br>large mansion<br>apartment<br>houseboat<br><br>Example 6: Using built-in functions<br><br>awk &#39;{<br>  split($0,t,&quot;:&quot;); #split(string, array [, fieldsep [, seps ] ])<br>  arr[count]=t[3];<br>  count++ <br>  } <br>  END { <br>    for(m in arr) <br>      print arr[m] <br>  } &#39; houses.txt<br><br>New York<br>Vermont<br>London<br>San Diego<br><br>Example 7: Using built-in variables<br><br>awk -F &#39;:&#39; &#39; <br>  {print FILENAME , &quot;Line&quot;, NR, &quot;has&quot;, NF, &quot;fields&quot; , &quot;and Field Separator is&quot;, FS}<br>&#39; houses.txt<br><br>houses.txt Line 1 has 4 fields and Field Separator is :<br>houses.txt Line 2 has 4 fields and Field Separator is :<br>houses.txt Line 3 has 4 fields and Field Separator is :<br>houses.txt Line 4 has 4 fields and Field Separator is :</pre><p><strong>sort—</strong>sorting file contents and printing the result in standard output.</p><pre>Syntax:<br>  sort [options] filename<br><br>Create a sample file:<br>echo -e &quot;1:Small house:Vermont:100 sqm\n2:Large house:San Diego:300 sqm\n3:Apartment:New York:70 sqm\n4:Houseboat:London:40 sqm&quot; &gt; houses.txt<br><br>Example 1: Sorting File Content<br><br>sort houses.txt <br><br>1:Small house:Vermont:100 sqm<br>2:Large house:San Diego:300 sqm<br>3:Apartment:New York:70 sqm<br>4:Houseboat:London:40 sqm<br><br>Example 2: Sorting File Contents in Reverse Order<br><br>sort -r houses.txt<br><br>4:Houseboat:London:40 sqm<br>3:Apartment:New York:70 sqm<br>2:Large house:San Diego:300 sqm<br>1:Small house:Vermont:100 sqm<br><br>Example 3: Sorting File Content Based on Fields<br><br>sort -t &quot;:&quot; -k2 houses.txt<br><br>3:Apartment:New York:70 sqm<br>4:Houseboat:London:40 sqm<br>2:Large house:San Diego:300 sqm<br>1:Small house:Vermont:100 sqm<br><br>Example 4: Sorting File Content Based on Numerical Fields and Reverse Order<br><br>sort -t &quot;:&quot; -nk4 houses.txt<br><br>2:Large house:San Diego:300 sqm<br>1:Small house:Vermont:100 sqm<br>3:Apartment:New York:70 sqm<br>4:Houseboat:London:40 sqm<br><br>Example 5: Sort a Stream Output<br><br>ls -ltr | sort -r -nk5<br><br>-rw-r--r--@ 1 karthik  karthik  196592730 18 Apr  2019 survey_results_public.csv<br>-rw-r--r--@ 1 karthik  karthik     420746 18 Apr  2019 so_survey_2019.pdf<br>-rw-r--r--@ 1 karthik  karthik       9857 18 Apr  2019 survey_results_schema.csv<br>-rw-r--r--@ 1 karthik  karthik       2268 20 May  2019 README_2019.txt</pre><p><strong>uniq—</strong>filters out the repeated lines in a file</p><pre>Syntax<br>  uniq [OPTIONS] [INPUT] [OUTPUT]<br><br>Create a sample file:<br><br>cat houses.txt <br><br>1:Small house:Vermont:100 sqm<br>2:Large house:San Diego:300 sqm<br>3:Apartment:New York:70 sqm<br>3:Apartment:New York:70 sqm<br>4:Houseboat:London:40 sqm<br>4:Houseboat:London:40 sqm<br><br>Example 1: Remove Duplicate Lines from a Text File<br><br>uniq houses.txt <br><br>1:Small house:Vermont:100 sqm<br>2:Large house:San Diego:300 sqm<br>3:Apartment:New York:70 sqm<br>4:Houseboat:London:40 sqm<br><br>Example 2: Count Duplicated Lines in a Text File<br><br>uniq -c houses.txt<br><br>1 1:Small house:Vermont:100 sqm<br>1 2:Large house:San Diego:300 sqm<br>2 3:Apartment:New York:70 sqm<br>2 4:Houseboat:London:40 sqm<br><br>Example 3: Print Only Duplicate Lines from a File<br><br>uniq -d houses.txt<br><br>3:Apartment:New York:70 sqm<br>4:Houseboat:London:40 sqm<br><br>Example 4: Print Only Unique Lines from a File<br><br>uniq -u houses.txt<br><br>1:Small house:Vermont:100 sqm<br>2:Large house:San Diego:300 sqm<br><br>Example 5: Remove Non-adjacent Duplicate Lines in File<br><br>cat houses.txt <br>1:Small house:Vermont:100 sqm<br>2:Large house:San Diego:300 sqm<br>3:Apartment:New York:70 sqm<br>3:Apartment:New York:70 sqm<br>4:Houseboat:London:40 sqm<br>4:Houseboat:London:40 sqm<br>1:Small house:Vermont:100 sqm<br><br>uniq houses.txt #uniq command works only when duplicate entries are adjacent.<br>1:Small house:Vermont:100 sqm<br>2:Large house:San Diego:300 sqm<br>3:Apartment:New York:70 sqm<br>4:Houseboat:London:40 sqm<br>1:Small house:Vermont:100 sqm<br><br>sort houses.txt| uniq #Use sort with unique to Remove Non-adjacent Duplicate Lines in File<br>1:Small house:Vermont:100 sqm<br>2:Large house:San Diego:300 sqm<br>3:Apartment:New York:70 sqm<br>4:Houseboat:London:40 sqm<br><br></pre><p><strong>grep</strong>—used to search for specific character patterns within text files or streams using regular expressions and display the matching lines.</p><pre>Syntax<br>  grep [options] pattern [files]<br><br>Create a sample file:<br>echo -e &quot;1:Small house:Vermont:100 sqm\n2:Large house:San Diego:300 sqm\n3:Apartment:New York:70 sqm\n4:Houseboat:London:40 sqm&quot; &gt; houses.txt<br><br>Example 1: Search and Filter Files content<br><br>grep &quot;house&quot; houses.txt <br>1:Small house:Vermont:100 sqm<br>2:Large house:San Diego:300 sqm<br><br>grep -v &quot;house&quot; houses.txt       #invert it&#39;s output<br>3:Apartment:New York:70 sqm<br>4:Houseboat:London:40 sqm<br><br>Example 2: Count the Number of Matches<br>grep -c &quot;house&quot; houses.txt <br>2<br><br>Example 3: Displays the line number in the file of the given search string<br>grep -n &quot;house&quot; houses.txt<br>1:1:Small house:Vermont:100 sqm<br>2:2:Large house:San Diego:300 sqm<br><br>Example 4: Display the Number of Lines Before or|and After the Search String<br><br>grep -A 1 &quot;Large&quot; houses.txt #after the search string<br>2:Large house:San Diego:300 sqm<br>3:Apartment:New York:70 sqm<br><br>grep -B 1 &quot;Large&quot; houses.txt #before the search string<br>1:Small house:Vermont:100 sqm<br>2:Large house:San Diego:300 sqm<br><br>grep -C 1 &quot;Large&quot; houses.txt #after and before the search string<br>1:Small house:Vermont:100 sqm<br>2:Large house:San Diego:300 sqm<br>3:Apartment:New York:70 sqm<br><br>Example 5: Search a string Recursively in all Directories<br>grep -r &quot;Linux Troubleshooting&quot; *<br><br>Example 6: Search for the Entire Pattern<br>karthik@karthik % grep -w &quot;Apartment&quot; houses.txt<br>3:Apartment:New York:70 sqm<br>karthik@karthik % grep -w &quot;Apart&quot; houses.txt #we are not searching for a pattern, but an entire word.<br>karthik@karthik % </pre><p><strong>cut—</strong>performs filtering based on the byte position, character, field, and delimiter.</p><pre>Syntax<br>  cut &lt;OPTIONS&gt;... [FILE-1] [FILE-2] ...<br><br>Create a sample file:<br>echo -e &quot;1:Small house:Vermont:100 sqm\n2:Large house:San Diego:300 sqm\n3:Apartment:New York:70 sqm\n4:Houseboat:London:40 sqm&quot; &gt; houses.txt<br><br>Example 1: Cut a String by Delimiter in Linux<br><br>cut -d &quot;:&quot; -f 3 houses.txt<br><br>Vermont<br>San Diego<br>New York<br>London<br><br>Example 2: Print a Range of characters of File<br><br>cut -c 3-13 houses.txt<br><br>Small house<br>Large house<br>Apartment:N<br>Houseboat:L<br><br>Example 3: Print First Byte of File<br><br>cut -b 1  houses.txt <br><br>1<br>2<br>3<br>4<br><br>Example 4: Print Specify Start Byte Position of File<br><br>cut -b 3- houses.txt #print all bytes starting from position 3<br><br>Small house:Vermont:100 sqm<br>Large house:San Diego:300 sqm<br>Apartment:New York:70 sqm<br>Houseboat:London:40 sqm</pre><p><strong>find</strong> — used to search for files and directories within a file system hierarchy based on specific user-defined criteria like name, size, type, or modification date.</p><pre><br>Syntax:<br>  find &lt;path&gt; &lt;criteria&gt; -exec &lt;command&gt; {} \;<br><br>Find Files and Directories Based on Size<br><br>Example 1: To find all 100MB files<br>find / -type f -size +100M<br><br>Example 2: To find all the files which are greater than 50MB and less than 100MB.<br>find / -size +50M -size -100M<br><br>Example 3: To find all .mp3 files with more than 10MB and delete them<br>find / -type f -name *.mp3 -size +10M -exec rm {} \; #One rm command invocation per file. <br><br>Find Files and Directories Based on Date and Time<br>  *Access time: -atime n and -amin n.<br>  *Changed time: -ctime n and -cmin n.<br>  *Modification time: -mtime n and -mmin n.<br><br>Example 1: To find all the files which are modified in the last 1 hour.<br>find / -mmin -60<br><br>Example 2: To find all the files which are modified 50 days back.<br>find / -mtime +50<br><br>Example 3: To find all the files which are modified more than 50 days back and less than 100 days.<br>find / -mtime +50 –mtime -100</pre><p><strong>Xargs</strong> — a powerful utility for building a command line; it can help you pass output of one command as an argument of another command for processing</p><pre>Syntax:<br>  command1 | xargs &lt;command2&gt;<br><br>Example 1: To know the number of lines/words/characters in each file in the list<br>ls *upload* | xargs wc<br><br>Example 2: Delete (Bulk) all .log files in a directory.<br>find . -type f -name &quot;*.txt&quot; | xargs rm #output of command1 will be appended here</pre><p><strong>Crontab</strong> — utility used for Task Scheduling and Task Automation</p><pre>syntax:<br>  MIN HOUR DOM MON DOW CMD<br><br>Special Characters:<br>  * -&gt; Matches any value in the field.<br>  , -&gt; Used to specify multiple values in a field.<br>  - -&gt; Used to specify a range of values.<br>  / -&gt; Used to specify a step value<br><br>Example 1: Run CMD every 5 mins<br>*/5 * * * * CMD<br><br>Example 2: Run CMD at 09:00 and 18:00 every day<br>00 9,18 * * * CMD<br><br>Example 3: Run CMD every day (excluding weekends) during the working hours 9 a.m – 6 p.m<br>00 9-18 * * 1-5<br><br>Example 4: Run CMD on 28th January at 10:10 AM<br>10 10 28 1 * CMD<br><br>Example 5: Run CMD every hour<br>0 1 * * * CMD (or) @hourly CMD<br><br>Example 6: Run CMD every day<br>0 0 1 * * CMD (or) @daily CMD<br><br>Example 7: Run CMD every year<br>0 0 1 1 * CMD (or) @yearly CMD</pre><p><strong>Socket Statistics—</strong>used to investigate network sockets and display detailed protocol statistics</p><pre>  ss -&gt; by default non-listening sockets<br>  ss -l -&gt; display listening sockets<br>  ss -a -&gt; display both listening and non-listening sockets<br>    Key Options:<br>      -t -&gt; TCP<br>      -u -&gt; UDP<br>      -s -&gt; Summary statistics<br><br>Example 1: Counts number of TCP states (e.g., ESTABLISHED)<br>ss -atH | awk &#39;{print $1}&#39; | sort | uniq -c<br>      8 ESTAB<br>      5 LISTEN<br>Example 2: Shows all listening TCP/UDP ports and count <br>ss -ltuH | awk &#39;{print $1}&#39; | sort | uniq -c<br>      5 tcp<br>      7 udp</pre><p><strong>lsof</strong>— used to find out which files are open by which Linux process.</p><pre>lsof -&gt; by default List All Open Files<br>lsof -u &lt;user&gt; -&gt; List User Specific Opened Files<br>lsof -i -&gt; List all Network Connections<br>lsof -i -P -n -&gt;  Prevent port numbers/networks from being changed to port names/host names<br><br>Example 1: How do you check which process is using a specific Port (e.g., 8080)?<br>lsof -i :8080 </pre><p><strong>mtr and traceroute</strong> — Monitoring Network Latency Between Microservices at the OS Level</p><p><strong>mtr</strong> combines two classic tools:<br> <strong>ping</strong>—checks if a host is reachable and measures round-trip time<br> <strong>traceroute</strong>—shows every router (“hop”) your data passes through</p><p><strong>tcpdump</strong> sits at your <strong>network interface</strong> and records every single packet that flows in and out — with precise timestamps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RikoOQyEcYKxq2rM2Db14A.png" /></figure><pre>#The Setup: Two Microservices<br>[Service A]  192.168.1.10  (e.g., Order Service)<br>      ↕  ← we want to measure latency here<br>[Service B]  192.168.1.20  (e.g., Payment Service)<br><br><br># Basic usage — replace IP with your target service<br>mtr 192.168.1.20<br># This opens a live screen that refreshes every second. To get a clean report instead:<br>mtr --report --report-cycles 50 192.168.1.20<br>#             └── send 50 probes, then print summary<br><br><br># Run this on Service A<br># Capture packets going to/from Service B (192.168.1.20) on port 8080<br>tcpdump -i eth0 host 192.168.1.20 and port 8080 -tttt<br>#        └─ network    └─ filter by IP        └─ └─ show full timestamps<br>#           interface                              and port</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=222e85272c1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Complex Enum — Made simple]]></title>
            <link>https://medium.com/@karthikn.js/java-complex-enum-made-simple-dfc0e067e437?source=rss-9f0aa679b51e------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfc0e067e437</guid>
            <category><![CDATA[java-enum]]></category>
            <category><![CDATA[java-21-features]]></category>
            <dc:creator><![CDATA[Karthikn]]></dc:creator>
            <pubDate>Tue, 28 Jan 2025 08:09:18 GMT</pubDate>
            <atom:updated>2025-01-28T08:09:18.585Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java Complex Enum — Made simple</h3><p><strong>An Enum in Java is a class-based construct</strong> that signifies a collection of values. One may interpret “collection of values” as a “collection of Enum instances,” indicating that an Enum can possess instance variables, methods, and a constructor to initialize those instance variables.</p><pre>public class EnumDemo {<br><br>    enum ABC{<br><br>        //Enum Instances with initialization<br>        abc1(&quot;one&quot;), abc2(&quot;two&quot;), abc3(&quot;three&quot;), abc4(null);<br><br>        //Instance Variables<br>        private String name;<br><br>        //Constructors.<br>        private ABC(String name) {<br>            this.name=name;<br>        }<br><br>        //Accessor Methods<br>        public String getName() {<br>            return name;<br>        }<br>    }<br>    <br>    public static void main (String[] arg){<br><br>        //Enum.instance.instanceMethod() <br>        System.out.println(ABC.abc1.getName()); //one<br><br>        //initializing a Enum instance<br>        ABC.abc4.name=&quot;four&quot;;<br><br>        System.out.println(ABC.abc4.getName()); //four<br>    }<br>}</pre><p>It is important to note two things:</p><ol><li>The list of values (Enum instances) always comes first.</li><li>Enum constructors are deemed <strong><em>private</em></strong> by default. This is due to the fact that instances of the enum are declared within the enum itself. Hence, the constructor can only be invoked within the enum.</li></ol><p><strong>An enum can implement an interface:</strong></p><p>Here, getName() method is overridden</p><pre>public class EnumDemo {<br><br>    interface InABC{<br>        public String getName();<br>    }<br><br>    enum ABC implements InABC {<br><br>        //Enum Instances with initialization<br>        abc1(&quot;one&quot;), abc2(&quot;two&quot;), abc3(&quot;three&quot;), abc4(null);<br><br>        //Instance Variables<br>        private String name;<br><br>        //Constructors.<br>        private ABC(String name) {<br>            this.name=name;<br>        }<br><br>        @Override<br>        public String getName() {<br>            return name;<br>        }<br>    }<br><br>    public static void main (String[] arg){<br><br>        System.out.println(ABC.abc1.getName()); //one<br>        System.out.println(ABC.abc2.getName()); //two<br>        System.out.println(ABC.abc3.getName()); //three<br>        ABC.abc4.name=&quot;four&quot;;<br>        System.out.println(ABC.abc4.getName()); //four<br>    }<br>}</pre><p><strong>Define different methods for each enum:</strong></p><p>We can keep track of the <strong>name </strong>through instance variables (as shown above), or we can let each enum value manage <strong>name</strong> itself. You can compare the code below with the code above.</p><pre>public class EnumDemo {<br><br>    enum ABC {<br>        abc1 { public String getName() { return &quot;one&quot;;}},<br>        abc2 { public String getName() { return &quot;two&quot;;}},<br>        abc3 { public String getName() { return &quot;three&quot;;}},<br>        abc4 { public String getName() { return &quot;four&quot;;}};<br>        public abstract String getName();<br>    }<br><br>    public static void main (String[] arg){<br><br>        System.out.println(ABC.abc1.getName()); //one<br>        System.out.println(ABC.abc2.getName()); //two<br>        System.out.println(ABC.abc3.getName()); //three<br>        System.out.println(ABC.abc4.getName()); //four<br>    }<br>}</pre><p>It is important to note two things when you want to define different methods for each enum</p><ol><li>Define an abstract method.</li><li>Each and every enum value is required to implement this method</li></ol><p>But what if we don’t want each and every enum value to have a method? No problem. We can create an implementation for all values and override it only for the special cases.</p><pre>public class EnumDemo {<br><br>    enum ABC {<br>        abc1 { public String getName() { return &quot;one&quot;;}},<br>        abc2 { public String getName() { return &quot;two&quot;;}},<br>        abc3, abc4;<br>        public String getName() { return &quot;No Name&quot;;}<br>    }<br><br>    public static void main (String[] arg){<br><br>        System.out.println(ABC.abc1.getName()); //one<br>        System.out.println(ABC.abc2.getName()); //two<br>        System.out.println(ABC.abc3.getName()); //No Name<br>        System.out.println(ABC.abc4.getName()); //No Name<br>    }<br>}</pre><p>I hope you now have a solid understanding of creating Enum variables, declaring enum constructors, and writing enum methods. Please feel free to reach out and discuss any of these topics with me if you’d like further clarification or details.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfc0e067e437" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Pattern Matching with Records]]></title>
            <link>https://medium.com/@karthikn.js/java-pattern-matching-with-records-f3c0df4d8a72?source=rss-9f0aa679b51e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3c0df4d8a72</guid>
            <category><![CDATA[java-21-features]]></category>
            <dc:creator><![CDATA[Karthikn]]></dc:creator>
            <pubDate>Thu, 23 Jan 2025 04:41:26 GMT</pubDate>
            <atom:updated>2025-01-23T04:41:26.868Z</atom:updated>
            <content:encoded><![CDATA[<p>This blog is a follow-up to my <a href="https://medium.com/@karthikn.js/java-encapsulating-data-with-records-ee69e04f5d60">previous post</a> about Java Records. Here, we’ll examine how pattern matching works with Java Records.</p><p>New to Java 21, records have been updated to support pattern matching. Let’s try an example:</p><pre>record Person(String name, int age, List&lt;String&gt; address) { }<br><br>public class JavaRecordPatternMatch {<br><br>    public static void main (String[] arg){<br><br>        Person p1 = new Person(&quot;TOM&quot;,9, List.of(&quot;Street&quot;,&quot;LandMark&quot;,&quot;City&quot;, &quot;pincode&quot;));<br><br>        //simple pattern matching<br>        if(p1 instanceof Person per){<br>            System.out.println(&quot;Name:&quot; + per.name() + &quot; , &quot; + &quot;Age:&quot; + per.age() + &quot; , &quot; + &quot;Address:&quot; + per.address().toString());<br>        }<br>    }<br>}</pre><p>This is just <strong>simple pattern matching</strong>. This allows us to use reference variable.</p><h4>Pattern Matching Records with fields</h4><p>We can also define a pattern that is compatible with the <strong>Person</strong> record. We also named three fields <strong>na, ag, and addr</strong>, this allows us to use them as local variables, without a reference variable.</p><pre> //pattern matching with records field<br> if(p1 instanceof Person(String na, int ag, List&lt;String&gt; addr)) {<br>       System.out.println(&quot;Name:&quot; + n + &quot; , &quot; + &quot;Age:&quot; + a + &quot; , &quot; + &quot;Address:&quot; + addr.toString());<br> }</pre><h4>Pattern Matching Records with var</h4><p>You can also use <strong>var</strong> in a pattern matching record. Let’s apply this to our previous examples. When <strong>var</strong> is used for one of the fields of the record, the compiler assumes the type to be the exact match for the type in the record.</p><pre> //pattern matching records with var<br> if(p1 instanceof Person(var na, var ag, var addr)) {<br>       System.out.println(&quot;Name:&quot; + na + &quot; , &quot; + &quot;Age:&quot; + ag + &quot; , &quot; + &quot;Address:&quot; + addr.toString());<br> }</pre><h4>Pattern Matching Records with var and Generic</h4><p>Pattern matching generics within records follow the similar rules for overloading generic methods.</p><pre> //pattern matching records with var and generic<br> if(p1 instanceof Person(var na, var ag, List&lt;? extends Object&gt; addr)) {<br>       System.out.println(&quot;Name:&quot; + na + &quot; , &quot; + &quot;Age:&quot; + ag + &quot; , &quot; + &quot;Address:&quot; + addr.toString());<br>  }</pre><h4>Pattern Matching Records with field, var, Generic and (Optional) Conditional Clause</h4><p>Let’s combine all</p><pre> //pattern matching records with var and generic and conditional clause<br> if(p1 instanceof Person(String na, var ag, List&lt;? extends Object&gt; addr) &amp;&amp; na.startsWith(&quot;T&quot;)) {<br>       System.out.println(&quot;Name:&quot; + na + &quot; , &quot; + &quot;Age:&quot; + ag + &quot; , &quot; + &quot;Address:&quot; + addr.toString());<br> }</pre><h4>Applying Pattern Matching Records to Switch</h4><p>One of the biggest new features of Java 21 is that pattern matching has been extended to switch. <strong><em>Any object reference type is permitted</em></strong>, provided the <strong>switch</strong> makes use of pattern matching.</p><p>To use pattern matching with a switch</p><ol><li>start with an object reference variable.</li><li>Apply acceptable types</li><li>Ordering switch Branches</li><li>Exhaustive switch Statements</li><li>Handling a null Case</li></ol><pre>record PMS(Object data) {}<br><br>public class PatternMatchingSwitch {<br><br>    public static long showData(PMS d) {<br><br>        return switch(d) {<br>            case PMS(Long l)    -&gt; l + 1;<br>            case PMS(Integer i) when i &gt; 5 -&gt; i + 10;<br>            case PMS(Number n)  -&gt; n.intValue() + 100;<br>            case PMS(Object o)  -&gt; 0;<br>            case null -&gt; -1;<br>            default -&gt; -2; // Not required if all types are covered in the pattern matching expression<br>        };<br>    }<br><br>    public static void main (String[] arg){<br><br>        System.out.println(&quot;Integer &quot; + showData(new PMS(10)));  //Integer 20<br>        System.out.println(&quot;Long &quot; + showData(new PMS(20L)));    //Long 21<br>        System.out.println(&quot;Number &quot; + showData(new PMS(30.0))); //Number 130<br>        System.out.println(&quot;Object &quot; + showData(new PMS(&quot;PMS&quot;)));//Object 0<br>        System.out.println(&quot;Null &quot; + showData(null));            //Null -1<br><br>    }<br>}</pre><p>I hope this blog provided you with a clearer understanding of the Java Pattern Matching with Records</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3c0df4d8a72" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Encapsulating Data with Records]]></title>
            <link>https://medium.com/@karthikn.js/java-encapsulating-data-with-records-ee69e04f5d60?source=rss-9f0aa679b51e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee69e04f5d60</guid>
            <category><![CDATA[java-21-features]]></category>
            <dc:creator><![CDATA[Karthikn]]></dc:creator>
            <pubDate>Tue, 21 Jan 2025 16:48:16 GMT</pubDate>
            <atom:updated>2025-01-21T16:48:16.534Z</atom:updated>
            <content:encoded><![CDATA[<h4>What is Encapsulation?</h4><p>The primary purpose of encapsulation is to hide the internal details and implementation of an object from the outside world, allowing the object to manage its own state and behavior. This promotes data hiding, reduces dependencies, and enhances code maintainability and security</p><p>Let’s create a simple POJO with two fields:1</p><pre>1:public final class BankAccount {    <br>2:    // Encapsulated data<br>3:    private final double balance;<br>4:    private final String name;<br>5:    // Constructor to initialize the balance<br>6:    public BankAccount(double balance, String name) {<br>7:        if(balance &gt; 0)<br>8:            this.balance = balance;<br>9:        else<br>10:            throw new IllegalArgumentException();<br>11:        this.name = name;<br>12:    }<br>13:    // Method to get the current balance<br>14:    public double getBalance() {<br>15:        return balance;<br>16:    }    <br>17:    // Method to get the name<br>18:    public String getName(){<br>19:        return name;<br>20:    }<br>21:}</pre><p>In the above example, <strong>data is private and getters or accessor are public</strong>. You might have noticed that <strong>we marked the class and its instance variables final</strong>, and we don’t have any mutator or setters methods, to modify the value of the instance variables. That’s because we want our class to be <strong>immutable</strong> in addition to being well encapsulated.</p><h4>Applying Records</h4><pre>public record BankAccount(double balance, String name){}</pre><p>Our BankAccount class was <strong>17 lines</strong> long. We can write that much more concisely, putting aside the guard clause on balance in the constructor for a moment, <strong>this BankAccount</strong> <strong>record is equivalent and immutable!</strong></p><p>It’s only one line long! Amazing, Isn’t it?. <strong>A record is a special type of data-oriented class in which the compiler inserts boilerplate code for you</strong>.</p><p>In fact, the compiler inserts much more than the 16 lines we wrote earlier. As a bonus, the compiler inserts useful implementations of the Object methods equals(), hashCode(), and toString()</p><h3>Declaring Constructors</h3><p><strong>Long Constructor</strong></p><p>The compiler normally inserts constructor automatically, which we refer to as the <strong><em>long constructor</em></strong>.</p><pre>public record BankAccount(double balance,String name){<br>    public BankAccount(double balance, String name) {<br>        if(balance &gt; 0)<br>            this.balance = balance;<br>        else<br>            throw new IllegalArgumentException();<br>        this.name = name;<br>    }<br>}</pre><p>We can just declare the constructor. The compiler will not insert a constructor if you define one with the same list of parameters in the same order. <strong>Since each field is final, the constructor must set every field.</strong></p><p><strong>Compact Constructor.</strong></p><p>Declaring a constructor is a nice feature of records, it’s also problematic. If we have 10 fields, we will need to declare assignments for every one, <strong>introducing the boilerplate</strong>. Luckily, Java added the ability to define a compact constructor for records</p><p>A <em>compact constructor</em> is a special type of constructor used for <strong>records to process validation and transformations </strong>concisely. It takes no parameters and implicitly sets all fields.</p><pre>public record BankAccount(double balance,String name){<br>    public BankAccount{ //No parentheses or constructor parameter<br>        if(balance&lt;0) // validations. Refers to input parameters, not instance members<br>            throw new IllegalArgumentException();<br>        name=name.toUpperCase(); // transformations. Refers to input parameters, not instance members<br>    }<br>    //Long Constructor implicitly called at end of compact constructor<br>}</pre><p>While compact constructors can modify the constructor parameters, <strong><em>they cannot modify the fields of the record</em>.</strong></p><pre>public record BankAccount(double balance,String name){<br>    public BankAccount{ <br>        this.balance = balance; // DOES NOT COMPILE<br>        this.name=name; // DOES NOT COMPILE<br>    }    <br>}</pre><h4><strong>Explicit Declaration of Records</strong></h4><p><strong>Class Members</strong></p><p>You can explicitly declare any of the members, such as the public accessor methods that correspond to the record class&#39;s components, for example:</p><pre>public record BankAccount(double balance,String name){<br>    <br>    // Public accessor method<br>    public double getBalance() {<br>        return balance;<br>    }<br>}</pre><p><strong>Static fields, Static initializers, and Static methods</strong></p><p>You can declare static fields, static initializers, and static methods in a record class, for example:</p><pre>public record BankAccount(double balance,String name){<br><br>    // Static field<br>    private static int counter;<br>    // Static initializer<br>    static {  counter = 1;  }<br>    // Static method<br>    public static BankAccount createAccount(double bal) {<br>        return new BankAccount(bal*counter, &quot;Karthik&quot;);<br>    }<br>}</pre><p><strong>Instance variables and Instance initializers</strong></p><p>You cannot declare instance variables (non-static fields) or instance initializers in a record class, for example, the following record class declaration <strong>doesn’t compile</strong>:</p><pre>public record BankAccount(double balance,String name){<br><br>    // Instance field declarations must be static:<br>    private int counter;<br>    // Instance initializers are not allowed in records:<br>    {  counter = 1;  }<br>}</pre><p>I hope this blog provided you with a clearer understanding of the foundational elements of the Java Record Class.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee69e04f5d60" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Oracle23ai Database Vector Search Integration with LangChain — part-2]]></title>
            <link>https://medium.com/@karthikn.js/oracle23ai-database-vector-search-integration-with-langchain-part-2-668445b51996?source=rss-9f0aa679b51e------2</link>
            <guid isPermaLink="false">https://medium.com/p/668445b51996</guid>
            <dc:creator><![CDATA[Karthikn]]></dc:creator>
            <pubDate>Thu, 03 Oct 2024 03:01:03 GMT</pubDate>
            <atom:updated>2024-10-03T03:01:03.480Z</atom:updated>
            <content:encoded><![CDATA[<h3>Oracle23ai Database Vector Search Integration with LangChain — part-2</h3><p>In this blog, we explored how to leverage the power of Oracle 23ai Database, utilizing LangChain, to efficiently store vectors and conduct similarity searches. It is recommended that you complete <a href="https://medium.com/@karthikn.js/oracle23ai-databasevector-search-integration-with-langchain-01dddfbfa1ea">part-1</a> of the work before reading ahead</p><p><strong>Step 1: Define a list of Documents</strong></p><pre>documents_json_list = [<br>        {<br>            &quot;id&quot;: &quot;cncpt_15.5.3.2.2_P4&quot;,<br>            &quot;text&quot;: &quot;If the answer to any preceding questions is yes, then the database stops the search and allocates space from the specified tablespace; otherwise, space is allocated from the database default shared temporary tablespace.&quot;,<br>            &quot;link&quot;: &quot;https://docs.oracle.com/en/database/oracle/oracle-database/23/cncpt/logical-storage-structures.html#GUID-5387D7B2-C0CA-4C1E-811B-C7EB9B636442&quot;,<br>        },<br>        {<br>            &quot;id&quot;: &quot;cncpt_15.5.5_P1&quot;,<br>            &quot;text&quot;: &quot;A tablespace can be online (accessible) or offline (not accessible) whenever the database is open.\nA tablespace is usually online so that its data is available to users. The SYSTEM tablespace and temporary tablespaces cannot be taken offline.&quot;,<br>            &quot;link&quot;: &quot;https://docs.oracle.com/en/database/oracle/oracle-database/23/cncpt/logical-storage-structures.html#GUID-D02B2220-E6F5-40D9-AFB5-BC69BCEF6CD4&quot;,<br>        },<br>    ]</pre><p><strong>Step 2: Create a LangChain Documents</strong></p><pre>documents_langchain = []<br>for doc in documents_json_list:<br>    metadata = {&quot;id&quot;: doc[&quot;id&quot;], &quot;link&quot;: doc[&quot;link&quot;]}<br>    doc_langchain = Document(page_content=doc[&quot;text&quot;], metadata=metadata)<br>    documents_langchain.append(doc_langchain)</pre><p><strong>Step 3: Create Vector Store from Documents</strong></p><pre>vector_store = OracleVS.from_documents(<br>    documents_langchain,<br>    model,<br>    client=conn,<br>    table_name=&quot;DOCUMENTS_COSINE&quot;,<br>    distance_strategy=DistanceStrategy.COSINE,<br>)</pre><p>Once the operation is complete, you will find a new table within the database, labeled “DOCUMENTS_COSINE”. <strong>Please Note</strong>: Various distance metrics are supported by Oracle, <a href="https://docs.oracle.com/en/database/oracle/oracle-database/23/vecse/create-vector-indexes-and-hybrid-vector-indexes.html">as documented</a>.</p><p><strong>Step 4: You may add documents to the Vector Store, if you so choose.</strong></p><pre>documents_json_list1 = [<br>    {<br>        &quot;id&quot;: &quot;cncpt_22.3.4.3.1_P2&quot;,<br>        &quot;text&quot;: &quot;The database stores LOBs differently from other data types. Creating a LOB column implicitly creates a LOB segment and a LOB index. The tablespace containing the LOB segment and LOB index, which are always stored together, may be different from the tablespace containing the table.\nSometimes the database can store small amounts of LOB data in the table itself rather than in a separate LOB segment.&quot;,<br>        &quot;link&quot;: &quot;https://docs.oracle.com/en/database/oracle/oracle-database/23/cncpt/concepts-for-database-developers.html#GUID-3C50EAB8-FC39-4BB3-B680-4EACCE49E866&quot;,<br>    },<br>    {<br>        &quot;id&quot;: &quot;cncpt_22.3.4.3.1_P3&quot;,<br>        &quot;text&quot;: &quot;The LOB segment stores data in pieces called chunks. A chunk is a logically contiguous set of data blocks and is the smallest unit of allocation for a LOB. A row in the table stores a pointer called a LOB locator, which points to the LOB index. When the table is queried, the database uses the LOB index to quickly locate the LOB chunks.&quot;,<br>        &quot;link&quot;: &quot;https://docs.oracle.com/en/database/oracle/oracle-database/23/cncpt/concepts-for-database-developers.html#GUID-3C50EAB8-FC39-4BB3-B680-4EACCE49E866&quot;,<br>    },<br>]<br><br># Create Langchain Documents to add documents<br>documents_langchain1 = []<br>for doc in documents_json_list1:<br>    metadata = {&quot;id&quot;: doc[&quot;id&quot;], &quot;link&quot;: doc[&quot;link&quot;]}<br>    doc_langchain = Document(page_content=doc[&quot;text&quot;], metadata=metadata)<br>    documents_langchain1.append(doc_langchain)<br><br># add document to the vector store<br>vector_store.add_documents(documents_langchain1);</pre><p><strong>Step 5: Create Index with 8 Parallel Workers and Target Accuracy as 97 %</strong></p><pre>oraclevs.create_index(<br>    conn,<br>    vector_store,<br>    params={&quot;idx_name&quot;: &quot;hnsw_idx1&quot;, &quot;idx_type&quot;: &quot;HNSW&quot;, &quot;accuracy&quot;: 97, &quot;parallel&quot;: 8,},<br>)</pre><p><strong>Step 6: Conduct Similarity searches</strong></p><pre>query = &quot;How are LOBS stored in Oracle Database&quot;;<br><br>print(vector_store.similarity_search(query, 2))</pre><p>The results of the similarity search will show you the documents that are most relevant to your query.”</p><p><strong>Please Note:</strong> It is important to always consult the <a href="https://python.langchain.com/api_reference/community/vectorstores/langchain_community.vectorstores.oraclevs.OracleVS.html#">oracle vector store documentation</a> before using it. This ensures that you have a clear understanding of how the API works and how to use it properly in your code. This can help prevent issues and save time.</p><p><strong>Complete python code and output:</strong></p><pre>import sys<br># pip install oracledb<br>import oracledb<br><br>#pip install langchain-community<br>from langchain_community.vectorstores import oraclevs<br>from langchain_community.vectorstores.oraclevs import OracleVS<br>from langchain_community.vectorstores.utils import DistanceStrategy<br>from langchain_core.documents import Document<br>from langchain_community.embeddings.oracleai import OracleEmbeddings<br><br># connect to oracle database<br>username = &quot;docuser&quot;<br>password = &quot;docuser&quot;<br>dsn = &quot;localhost:1521/FREEPDB1&quot;<br><br>try:<br>    conn = oracledb.connect(user=username, password=password, dsn=dsn)<br>    print(&quot;Connection successful!&quot;)<br>except Exception as e:<br>    print(&quot;Connection failed!&quot;)<br>    sys.exit(1)<br><br># use Oracle Provider ONNX model for embedding docs<br>embedder_params = {&quot;provider&quot;: &quot;database&quot;, &quot;model&quot;: &quot;ALL_MINILM_L12_V2&quot;}<br>model = OracleEmbeddings(conn=conn, params=embedder_params)<br><br><br># Define a list of documents (The examples below are random documents from Oracle Concepts Manual )<br>documents_json_list = [<br>        {<br>            &quot;id&quot;: &quot;cncpt_15.5.3.2.2_P4&quot;,<br>            &quot;text&quot;: &quot;If the answer to any preceding questions is yes, then the database stops the search and allocates space from the specified tablespace; otherwise, space is allocated from the database default shared temporary tablespace.&quot;,<br>            &quot;link&quot;: &quot;https://docs.oracle.com/en/database/oracle/oracle-database/23/cncpt/logical-storage-structures.html#GUID-5387D7B2-C0CA-4C1E-811B-C7EB9B636442&quot;,<br>        },<br>        {<br>            &quot;id&quot;: &quot;cncpt_15.5.5_P1&quot;,<br>            &quot;text&quot;: &quot;A tablespace can be online (accessible) or offline (not accessible) whenever the database is open.\nA tablespace is usually online so that its data is available to users. The SYSTEM tablespace and temporary tablespaces cannot be taken offline.&quot;,<br>            &quot;link&quot;: &quot;https://docs.oracle.com/en/database/oracle/oracle-database/23/cncpt/logical-storage-structures.html#GUID-D02B2220-E6F5-40D9-AFB5-BC69BCEF6CD4&quot;,<br>        },<br>    ]<br><br># Create Langchain Documents<br>documents_langchain = []<br>for doc in documents_json_list:<br>    metadata = {&quot;id&quot;: doc[&quot;id&quot;], &quot;link&quot;: doc[&quot;link&quot;]}<br>    doc_langchain = Document(page_content=doc[&quot;text&quot;], metadata=metadata)<br>    documents_langchain.append(doc_langchain)<br><br># Create vector store from Documents<br>vector_store = OracleVS.from_documents(<br>    documents_langchain,<br>    model,<br>    client=conn,<br>    table_name=&quot;Documents_COSINE&quot;,<br>    distance_strategy=DistanceStrategy.COSINE,<br>)<br><br># Define a list of documents to add documents to the vector store (The examples below are random documents from Oracle Concepts Manual )<br>documents_json_list1 = [<br>    {<br>        &quot;id&quot;: &quot;cncpt_22.3.4.3.1_P2&quot;,<br>        &quot;text&quot;: &quot;The database stores LOBs differently from other data types. Creating a LOB column implicitly creates a LOB segment and a LOB index. The tablespace containing the LOB segment and LOB index, which are always stored together, may be different from the tablespace containing the table.\nSometimes the database can store small amounts of LOB data in the table itself rather than in a separate LOB segment.&quot;,<br>        &quot;link&quot;: &quot;https://docs.oracle.com/en/database/oracle/oracle-database/23/cncpt/concepts-for-database-developers.html#GUID-3C50EAB8-FC39-4BB3-B680-4EACCE49E866&quot;,<br>    },<br>    {<br>        &quot;id&quot;: &quot;cncpt_22.3.4.3.1_P3&quot;,<br>        &quot;text&quot;: &quot;The LOB segment stores data in pieces called chunks. A chunk is a logically contiguous set of data blocks and is the smallest unit of allocation for a LOB. A row in the table stores a pointer called a LOB locator, which points to the LOB index. When the table is queried, the database uses the LOB index to quickly locate the LOB chunks.&quot;,<br>        &quot;link&quot;: &quot;https://docs.oracle.com/en/database/oracle/oracle-database/23/cncpt/concepts-for-database-developers.html#GUID-3C50EAB8-FC39-4BB3-B680-4EACCE49E866&quot;,<br>    },<br>]<br><br># Create Langchain Documents to add documents<br>documents_langchain1 = []<br>for doc in documents_json_list1:<br>    metadata = {&quot;id&quot;: doc[&quot;id&quot;], &quot;link&quot;: doc[&quot;link&quot;]}<br>    doc_langchain = Document(page_content=doc[&quot;text&quot;], metadata=metadata)<br>    documents_langchain1.append(doc_langchain)<br><br># add documents to the vector store<br>vector_store.add_documents(documents_langchain1);<br><br># create index<br>oraclevs.create_index(<br>    conn,<br>    vector_store,<br>    params={&quot;idx_name&quot;: &quot;hnsw_idx1&quot;, &quot;idx_type&quot;: &quot;HNSW&quot;, &quot;accuracy&quot;: 97, &quot;parallel&quot;: 16,}<br>);<br><br>#Conduct Similarity searches<br>query = &quot;How are LOBS stored in Oracle Database&quot;;<br>print(vector_store.similarity_search(query, 2))</pre><pre>/Users/demo/PycharmProjects/pythonProject/venv/bin/python /Users/demo/PycharmProjects/pythonProject/venv/OrclVS_SimpleStore.py <br>Connection successful!<br><br>[Document(metadata={&#39;id&#39;: &#39;cncpt_22.3.4.3.1_P2&#39;, &#39;link&#39;: &#39;https://docs.oracle.com/en/database/oracle/oracle-database/23/cncpt/concepts-for-database-developers.html#GUID-3C50EAB8-FC39-4BB3-B680-4EACCE49E866&#39;}, page_content=&#39;The database stores LOBs differently from other data types. Creating a LOB column implicitly creates a LOB segment and a LOB index. The tablespace containing the LOB segment and LOB index, which are always stored together, may be different from the tablespace containing the table.\nSometimes the database can store small amounts of LOB data in the table itself rather than in a separate LOB segment.&#39;), Document(metadata={&#39;id&#39;: &#39;cncpt_22.3.4.3.1_P3&#39;, &#39;link&#39;: &#39;https://docs.oracle.com/en/database/oracle/oracle-database/23/cncpt/concepts-for-database-developers.html#GUID-3C50EAB8-FC39-4BB3-B680-4EACCE49E866&#39;}, page_content=&#39;The LOB segment stores data in pieces called chunks. A chunk is a logically contiguous set of data blocks and is the smallest unit of allocation for a LOB. A row in the table stores a pointer called a LOB locator, which points to the LOB index. When the table is queried, the database uses the LOB index to quickly locate the LOB chunks.&#39;)]<br><br>Process finished with exit code 0</pre><p>You can modify the search terms and see if you get more relevant search results.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=668445b51996" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Oracle23ai Database Vector Search Integration with LangChain]]></title>
            <link>https://medium.com/@karthikn.js/oracle23ai-databasevector-search-integration-with-langchain-01dddfbfa1ea?source=rss-9f0aa679b51e------2</link>
            <guid isPermaLink="false">https://medium.com/p/01dddfbfa1ea</guid>
            <dc:creator><![CDATA[Karthikn]]></dc:creator>
            <pubDate>Thu, 26 Sep 2024 15:59:49 GMT</pubDate>
            <atom:updated>2024-09-30T06:54:02.398Z</atom:updated>
            <content:encoded><![CDATA[<p>LangChain is a powerful and flexible open source orchestration framework that helps developers build applications that leverage the advanced capabilities of large language models (LLMs).</p><p>Oracle AI Vector Search integrates with LangChain at various levels:</p><ul><li>Document Loaders</li><li>Text Splitter</li><li>Embeddings</li><li>Summary</li><li>Vector Store</li></ul><h3><strong>Prerequisites</strong></h3><ol><li>Install Oracle23ai — Check out this link:<a href="https://www.oracle.com/in/database/free/get-started/">https://www.oracle.com/in/database/free/get-started/</a></li><li>Download the <a href="https://adwc4pm.objectstorage.us-ashburn-1.oci.customer-oci.com/p/VBRD9P8ZFWkKvnfhrWxkpPe8K03-JIoM5h_8EJyJcpE80c108fuUjg7R5L5O7mMZ/n/adwc4pm/b/OML-Resources/o/all_MiniLM_L12_v2_augmented.zip%20unzip%20all-MiniLM-L12-v2_augmented.zip">pre-trained ONNX embedding model</a> and unzip it in your working folder.</li><li>Create User, Directory, Credentials, Grant privileges, Load ONNX formatted model and documents into Oracle database</li></ol><pre><br>CONN sys/&lt;password&gt;@pdb AS sysdba;<br><br>CREATE USER docuser IDENTIFIED BY docuser<br><br>GRANT DB_DEVELOPER_ROLE, CREATE MINING MODEL TO docuser;<br><br>CREATE OR REPLACE DIRECTORY dm_dump AS &#39;&lt;path to ONNX embedding model&gt;&#39;;<br><br>GRANT READ, WRITE ON DIRECTORY dm_dump TO docuser;<br><br>BEGIN<br>  DBMS_NETWORK_ACL_ADMIN.APPEND_HOST_ACE(<br>    host =&gt; &#39;*&#39;,<br>    ace =&gt; xs$ace_type(privilege_list =&gt; xs$name_list(&#39;connect&#39;),<br>                       principal_name =&gt; &#39;docuser&#39;,<br>                       principal_type =&gt; xs_acl.ptype_db));<br>END;<br>/<br><br>DECLARE<br>  jo json_object_t;<br>BEGIN<br>  jo := json_object_t();<br>  jo.put(&#39;access_token&#39;, &lt;access token&gt;); #Set up your credentials for the Cohere REST provider<br>  DBMS_VECTOR.CREATE_CREDENTIAL(<br>    credential_name   =&gt; &#39;COHERE_CRED&#39;,<br>    params            =&gt; json(jo.to_string));<br>END;<br>/<br>   <br>CONN docuser/docuser@pdb;<br><br>EXECUTE DBMS_VECTOR.LOAD_ONNX_MODEL(&#39;DM_DUMP&#39;, &#39;all_MiniLM_L12_v2.onnx&#39;, &#39;ALL_MINILM_L12_V2&#39;);<br><br>CREATE TABLE doc_tab (id number, DATA blob);<br><br>INSERT INTO doc_tab VALUES(1, to_blob(bfilename(&#39;dm_dump&#39;, &#39;oracle-ai-vector-search-users-guide.pdf&#39;)));</pre><h3><strong>Document Processing</strong></h3><p>The example below demonstrates how to load and chunk documents using the OracleDocLoader and OracleTextSplitter respectively:</p><pre>import sys<br># pip install oracledb<br>import oracledb <br><br>#pip install langchain-community<br>from langchain_community.document_loaders.oracleai import OracleDocLoader<br>from langchain_community.document_loaders.oracleai import OracleTextSplitter<br>from langchain_core.documents import Document<br><br># connect to oracle database<br>username = &quot;docuser&quot;<br>password = &quot;docuser&quot;<br>dsn = &quot;localhost:1521/FREEPDB1&quot;<br><br>try:<br>    conn = oracledb.connect(user=username, password=password, dsn=dsn)<br>    print(&quot;Connection successful!&quot;)<br>except Exception as e:<br>    print(&quot;Connection failed!&quot;)<br>    sys.exit(1)<br><br><br># loading from Oracle Database table<br>loader_params = {<br>    &quot;owner&quot;: &quot;docuser&quot;,<br>    &quot;tablename&quot;: &quot;doc_tab&quot;,<br>    &quot;colname&quot;: &quot;data&quot;,<br>}<br><br>&quot;&quot;&quot; load the docs &quot;&quot;&quot;<br>loader = OracleDocLoader(conn=conn, params=loader_params)<br>docs = loader.load()<br><br>&quot;&quot;&quot; verify &quot;&quot;&quot;<br>print(f&quot;Number of docs loaded: {len(docs)}&quot;)<br><br># split by default parameters<br>splitter_params = {&quot;split&quot;: &quot;sentence&quot;,&quot;normalize&quot;: &quot;all&quot;}<br><br># get the splitter instance<br>splitter = OracleTextSplitter(conn=conn, params=splitter_params)<br><br>list_chunks = []<br>for doc in docs:<br>    chunks = splitter.split_text(doc.page_content)<br>    list_chunks.extend(chunks)<br><br>&quot;&quot;&quot; verify &quot;&quot;&quot;<br>print(f&quot;Number of Chunks: {len(list_chunks)}&quot;)</pre><pre>/Users/demo/PycharmProjects/pythonProject/venv/bin/python /Users/demo/PycharmProjects/pythonProject/venv/OrclVS_LangChain.py <br>Connection successful!<br>Number of docs loaded: 1<br>Number of Chunks: 1544<br><br>Process finished with exit code 0</pre><h3>Generate Embeddings using ‘database’ provider</h3><p>The following sample code will show how to generate embeddings:</p><pre>import sys<br># pip install oracledb<br>import oracledb<br><br>#pip install langchain-community<br>from langchain_community.embeddings.oracleai import OracleEmbeddings<br>from langchain_core.documents import Document<br><br># connect to oracle database<br>username = &quot;docuser&quot;<br>password = &quot;docuser&quot;<br>dsn = &quot;localhost:1521/FREEPDB1&quot;<br><br>try:<br>    conn = oracledb.connect(user=username, password=password, dsn=dsn)<br>    print(&quot;Connection successful!&quot;)<br>except Exception as e:<br>    print(&quot;Connection failed!&quot;)<br>    sys.exit(1)<br><br># using ONNX model loaded to Oracle Database<br>embedder_params = {&quot;provider&quot;: &quot;database&quot;, &quot;model&quot;: &quot;ALL_MINILM_L12_V2&quot;}<br><br>embedder = OracleEmbeddings(conn=conn, params=embedder_params)<br>embed = embedder.embed_query(&quot;Hello World!&quot;)<br><br>&quot;&quot;&quot; verify &quot;&quot;&quot;<br>print(f&quot;Embedding generated by OracleEmbeddings: {embed}&quot;)</pre><pre>/Users/demo/PycharmProjects/pythonProject/venv/bin/python /Users/demo/PycharmProjects/pythonProject/venv/OrclVS_Embedding.py <br>Connection successful!<br>Embedding generated by OracleEmbeddings: [-0.072171174, 0.0380970463, -0.00109094463, -0.0586063676, 0.00146338763, -0.157873183, 0.0730511099, 0.0427136123, -0.0936905965, 0.0930458382, -0.0178093649, -0.0389041714, 0.07074669, -0.0224472024, -0.0806428045, -0.023059018, 0.0639552176, -0.0523527749, -0.0496960282, -0.0738851875, -0.0463187248, 0.0155538553, -0.0965902135, -0.00724394433, -0.0494297557, -0.0330428928, 0.00281107798, 0.0195569694, 0.0791323334, -0.0713232979, 0.0179149862, 0.0366576537, 0.103508331, -0.00443731621, -0.0452564023, 0.00134466588, 0.0504261628, -0.0292417258, 0.0344821401, 0.0796908587, 0.0216865446, 0.0230617225, -0.020420026, 0.0210238658, 0.0296038035, -0.0744746774, -0.00140556716, -0.0256613176, 0.0401422493, -0.0686227679, 0.00971524138, -0.04006413, 0.0386103466, -0.0359476879, 0.0758538917, -0.0458919145, -0.00786018092, 0.00181587576, 0.00393815013, -0.011239375, -0.0528322384, 0.0312963687, 0.0466702729, -0.0739965364, 0.0290149469, 0.00402658107, 0.0367627665, 0.0683176816, 0.0220987443, -0.0855077505, -0.0254405737, 0.0267733373, 0.0705894306, -0.0903470442, 0.0464828908, 0.0245375, 0.0597307421, 0.0196352955, -0.03003712, -0.0131737487, 0.0471646637, -0.116148755, 0.0439504087, 0.0617776215, 0.0414385647, 0.031435065, 0.010252594, 0.071059376, 0.0491396673, -0.0239396971, -0.0843567997, -0.0177502688, 0.0647060871, 0.01231746, -0.0526509769, 0.0367337577, 0.0309715718, 0.00328124943, -0.141123012, 0.201437801, -0.0789464265, 0.013179481, -0.0195147377, 0.0684700683, -0.0153352888, 0.0588567741, -0.0398837291, 0.0411281399, 0.0614496209, -0.0338177532, -0.0264139604, 0.0085619539, -0.0585131682, -0.0146481935, 0.0293918345, -0.0453676693, 0.013873131, 0.0544097163, 0.00599036785, 0.0347417705, -0.0109184301, -0.0116976202, 0.0269330721, -0.0544940867, 0.0370931588, -0.0425019599, 0.0107716592, 0.037030451, 0.0579123981, 0.0151843559, 0.0735981986, 0.143348217, -0.0339687988, -0.0256294943, 0.00252925791, -0.00670579122, 0.043027211, 0.00321942009, -0.00383376889, -0.0318826362, 0.0166075174, 0.0808276683, -0.0154005773, 0.04095608, 0.0264188461, -0.0723247305, 0.0641346425, -0.00717224507, 0.0410923846, 0.0526990257, -0.0493429229, 0.0165259931, 0.0129429819, 0.0105187902, 0.0981686935, -0.0469271876, -0.000284506619, 0.0413883403, 0.0375848338, -0.0313691236, -0.0484140627, 0.0340190977, -0.0214180369, -0.0260429177, -0.0287066624, -0.0182357021, 0.000846595154, -0.0499977395, -0.0380982384, -0.0020330213, 0.0247962587, -0.0536781475, -0.0186353493, -0.0645961761, 0.0515761636, 0.0279165953, -0.0216849204, 0.0253995825, 0.0158905741, 0.00726961764, -0.0713081509, 0.0413058959, 0.0224896688, 0.00995357428, 0.00688411435, 0.00930111948, -0.039853625, 0.00925479922, -0.0176044423, 0.05239724, 0.0791305378, 0.00011320725, 0.0182025321, -0.0358200483, -0.0203022752, 0.0277382825, 0.0361829586, 0.0144153032, 0.057792943, -0.0424232446, -0.0572057106, 0.00116845139, 0.0664251223, 0.0190988034, 0.149578273, -0.101353623, 0.000110350004, 0.0106112119, -0.0056752353, -0.0178068578, 0.0057362942, 0.0569409169, 0.00206893519, -0.0106750103, -0.0386816673, -0.0173727702, -0.0477955416, 0.0657697842, -0.0624060668, -0.0028268334, 0.0328429863, -0.0222820975, -0.02842094, 1.31276707e-34, 0.0500609651, 0.032837823, -0.0664500147, -0.116624348, 0.0047686114, 0.0233754851, -0.0289041381, 0.0697761625, -0.0273505002, 0.0644228533, -0.022041861, 0.00132045255, 0.0281035863, -0.0220604986, -0.0144153591, -0.0172293875, 0.104857072, 0.00176810636, -0.065085575, 0.0551853143, -0.04172986, -0.0248371791, -0.0404175632, -0.0240946747, -0.0411281399, -0.000498979294, -0.0314523578, 0.0383681655, -0.0925317034, 0.0326873027, -0.00330612832, 0.122557253, -0.00923820492, 0.0510994121, 0.0234723445, 0.0182647705, -0.0890566781, -0.165726468, -0.0269071646, 0.00512901042, -0.0543270893, -0.0102916025, -0.0342820957, 0.0648126751, -0.0800798759, -0.0024745455, -0.09303312, 0.0345547348, 0.0173080843, -0.121913113, -0.0673019439, -0.0478568487, 0.0446675569, -0.0708351731, -0.128835976, 0.0381415188, -0.0275400411, 0.0195926782, 0.00932138506, -0.0206561517, -0.0192970727, 0.0701968074, 0.105594017, 0.0738313869, 0.0864312127, 0.0112429494, 0.0773226395, 0.0437474698, 0.0472887829, -0.0513471365, -0.0665824786, 0.0465341657, -0.00366965355, 0.0293714851, -0.0276181437, 0.0372550972, 0.00511105033, -0.0317081511, -0.0207028203, 0.0251715612, 0.02636653, 0.0709035546, 0.0509266742, 0.0142389704, 0.0126219606, 0.0688502491, 0.0891755074, 0.047465276, -0.0501735546, -0.035285309, -0.00598408235, -0.0142314928, 0.0326677077, -0.0147046195, -0.0442683883, 6.89236272e-33, -0.0975364372, 0.0256942697, 0.06317316, -0.0217822492, 0.0578753687, 0.0397838019, 0.0146803968, 0.021232117, -0.129973605, -0.000308150018, -0.0137866875, 0.0829779953, -0.0345821679, -0.076466769, -0.0147514613, 0.020076951, -0.0847099274, 0.0299223978, 0.0525433756, -0.0548556782, 0.0216884855, 0.0341799669, -0.0132245384, 0.0214460213, 0.0861579105, -0.0448126867, -0.0640271828, -0.0612388737, -0.0330915898, -0.0922609046, 0.0235502515, 0.0130160619, -0.0772151276, 0.00517851207, -0.0904438198, -0.00904631242, -0.00668169744, -0.0285883006, 0.0427922271, -0.109483346, -0.0537137054, 0.00792330597, 0.0477838144, -0.0762667656, 0.0207456686, 0.0532300845, -0.0119099263, 0.0254606828, 0.0478653386, 0.000645511609, -0.00161233195, 0.0160644557, 0.0555278435, 0.00315105892, -0.00370255066, 0.00937949494, -0.00535022607, -0.0469130278, -0.0350692123, 0.0650923476, -0.0281642396, -0.0529256165, 0.010163716, 0.0371375345]<br><br>Process finished with exit code 0</pre><h3>Generate Summary using ‘Cohere’ Provider</h3><p>The following sample code will show how to generate summary:</p><pre>import sys<br># pip install oracledb<br>import oracledb<br><br>#pip install langchain-community<br>from langchain_community.utilities.oracleai import OracleSummary<br>from langchain_core.documents import Document<br><br># connect to oracle database<br>username = &quot;docuser&quot;<br>password = &quot;docuser&quot;<br>dsn = &quot;localhost:1521/FREEPDB1&quot;<br><br>try:<br>    conn = oracledb.connect(user=username, password=password, dsn=dsn)<br>    print(&quot;Connection successful!&quot;)<br>except Exception as e:<br>    print(&quot;Connection failed!&quot;)<br>    sys.exit(1)<br><br><br># using &#39;cohere&#39; provider<br>summary_params = {<br>    &quot;provider&quot;: &quot;cohere&quot;,<br>    &quot;credential_name&quot;: &quot;COHERE_CRED&quot;,<br>    &quot;url&quot;: &quot;https://api.cohere.com/v1/summarize&quot;,<br>    &quot;model&quot;: &quot;command&quot;,<br>}<br><br># get the summary instance<br># Remove proxy if not required<br>summ = OracleSummary(conn=conn, params=summary_params, proxy=&quot;xx.xx.xx.xx:xx&quot;)<br>summary = summ.get_summary(<br>    &quot;In the heart of the forest, &quot;<br>    + &quot;a lone fox ventured out at dusk, seeking a lost treasure. &quot;<br>    + &quot;With each step, memories flooded back, guiding its path. &quot;<br>    + &quot;As the moon rose high, illuminating the night, the fox unearthed &quot;<br>    + &quot;not gold, but a forgotten friendship, worth more than any riches.&quot;<br>)<br><br>print(f&quot;Summary generated by OracleSummary: {summary}&quot;)</pre><pre>/Users/demo/PycharmProjects/pythonProject/venv/bin/python /Users/demo/PycharmProjects/pythonProject/venv/OrclVS_Summary.py <br>Connection successful!<br>Summary generated by OracleSummary: [&#39;A fox goes on a quest in the forest at dusk, guided by memories of a lost treasure. During its search, the fox rediscovers a forgotten friendship that is more valuable than any treasure.&#39;]<br><br>Process finished with exit code 0</pre><p><strong>Please note:</strong> In this blog, I have covered Document Processing, Generating Embeddings and Generating Summary. I will cover Vector store in a separate blog.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01dddfbfa1ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Oracle23ai Database — use RAG to complement LLMs]]></title>
            <link>https://medium.com/@karthikn.js/oracle23ai-database-use-rag-to-complement-llms-0982b497b1a8?source=rss-9f0aa679b51e------2</link>
            <guid isPermaLink="false">https://medium.com/p/0982b497b1a8</guid>
            <dc:creator><![CDATA[Karthikn]]></dc:creator>
            <pubDate>Tue, 24 Sep 2024 11:42:20 GMT</pubDate>
            <atom:updated>2024-09-24T11:42:20.435Z</atom:updated>
            <content:encoded><![CDATA[<h3>Oracle23ai Database — use RAG to complement LLMs</h3><p>Oracle AI Vector Search supports Enterprise Retrieval Augmented Generation (RAG) to enable sophisticated queries that can combine vectors with relational data, graph data, spatial data, and JSON collections.</p><p>In this blog, we are going to see how to run a similarity search for specific documentation content based on a user query. Once documentation chunks are retrieved, they are concatenated and a prompt is generated to ask an Large Language Models (LLMs) to answer the user question using retrieved chunks.</p><p><strong>Step 1:</strong> Install Oracle23ai</p><ul><li>Check out this link:<a href="https://www.oracle.com/in/database/free/get-started/">https://www.oracle.com/in/database/free/get-started/</a></li></ul><p><strong>Step 2:</strong> Download the <a href="https://adwc4pm.objectstorage.us-ashburn-1.oci.customer-oci.com/p/VBRD9P8ZFWkKvnfhrWxkpPe8K03-JIoM5h_8EJyJcpE80c108fuUjg7R5L5O7mMZ/n/adwc4pm/b/OML-Resources/o/all_MiniLM_L12_v2_augmented.zip%20unzip%20all-MiniLM-L12-v2_augmented.zip">pre-trained ONNX embedding model</a> and unzip it in your working folder.</p><p><strong>Step 3:</strong> Create User, Grant privileges and Create Directory</p><pre>CONN sys/&lt;password&gt;@pdb AS sysdba;<br><br>CREATE USER docuser IDENTIFIED BY docuser<br><br>GRANT DB_DEVELOPER_ROLE, CREATE MINING MODEL TO docuser;<br><br>CREATE OR REPLACE DIRECTORY dm_dump AS &#39;&lt;path to ONNX embedding model&gt;&#39;;<br><br>GRANT READ, WRITE ON DIRECTORY dm_dump TO docuser;</pre><p><strong>Step 4:</strong> Grant connect privilege to allow connection to the host</p><pre>BEGIN<br>  DBMS_NETWORK_ACL_ADMIN.APPEND_HOST_ACE(<br>    host =&gt; &#39;*&#39;,<br>    ace =&gt; xs$ace_type(privilege_list =&gt; xs$name_list(&#39;connect&#39;),<br>                       principal_name =&gt; &#39;docuser&#39;,<br>                       principal_type =&gt; xs_acl.ptype_db));<br>END;<br>/</pre><p><strong>Step 5:</strong> Set the HTTP proxy server, if configured</p><pre>SQL&gt; EXEC UTL_HTTP.SET_PROXY(&#39;&lt;proxy-hostname&gt;:&lt;proxy-port&gt;&#39;);<br><br>PL/SQL procedure successfully completed.</pre><p><strong>Step 6:</strong> Set up your credentials for the Cohere REST provider</p><pre>SQL&gt; DECLARE<br>  jo json_object_t;<br>BEGIN<br>  jo := json_object_t();<br>  jo.put(&#39;access_token&#39;, &lt;access token&gt;);<br>  DBMS_VECTOR.CREATE_CREDENTIAL(<br>    credential_name   =&gt; &#39;COHERE_CRED&#39;,<br>    params            =&gt; json(jo.to_string));<br>END;<br>/<br>   <br>PL/SQL procedure successfully completed.</pre><p><strong>Step 7:</strong> Connect to Oracle Database as docuser and Load ONNX formatted model into Oracle database</p><pre>CONN docuser/docuser@pdb;<br><br>SQL&gt; EXECUTE DBMS_VECTOR.LOAD_ONNX_MODEL(&#39;DM_DUMP&#39;, &#39;all_MiniLM_L12_v2.onnx&#39;, &#39;ALL_MINILM_L12_V2&#39;);<br><br>PL/SQL procedure successfully completed.</pre><p><strong>Step 8:</strong> Generate Vector Embeddings</p><p>We are going to use PL/SQL package to convert pdf to embeddings, which involves a three-step process: <strong>convert a PDF file to text,</strong> <strong>split the text into chunks</strong>, and then <strong>create vector embeddings on each chunk</strong>.</p><pre>SQL&gt; CREATE TABLE doc_tab (id number, DATA blob);<br><br>Table created.<br><br>SQL&gt; INSERT INTO doc_tab<br>VALUES(1, to_blob(bfilename(&#39;DM_DUMP&#39;, &#39;oracle-ai-vector-search-users-guide.pdf&#39;)));<br><br>1 rows created.<br><br>SELECT dt.id doc_id,<br>       et.*<br>FROM doc_tab dt,<br>     dbms_vector_chain.utl_to_embeddings(dbms_vector_chain.utl_to_chunks(dbms_vector_chain.utl_to_text(dt.data)), json(&#39;{&quot;provider&quot;:&quot;database&quot;, &quot;model&quot;:&quot;ALL_MINILM_L12_V2&quot;}&#39;)) et</pre><p><strong>Step 9:</strong> Store Vector Embeddings</p><p>Creates a relational table (doc_chunks) from unstructured text chunks and the corresponding vector embeddings</p><pre>SQL&gt; CREATE TABLE doc_chunks (doc_id number, chunk_id number, chunk_data varchar2(4000),<br>                                                                    chunk_embedding vector);<br><br>Table created.<br><br>SQL&gt; INSERT INTO doc_chunks<br>SELECT dt.id doc_id,<br>       et.embed_id chunk_id,<br>       et.embed_data chunk_data,<br>       to_vector(et.embed_vector) chunk_embedding<br>FROM doc_tab dt,<br>     dbms_vector_chain.utl_to_embeddings(dbms_vector_chain.utl_to_chunks(dbms_vector_chain.utl_to_text(dt.data)), json(&#39;{&quot;provider&quot;:&quot;database&quot;, &quot;model&quot;:&quot;ALL_MINILM_L12_V2&quot;}&#39;)) t,<br>     JSON_TABLE(t.column_value, &#39;$[*]&#39; COLUMNS (embed_id NUMBER PATH &#39;$.embed_id&#39;, embed_data VARCHAR2(4000) PATH &#39;$.embed_data&#39;, embed_vector CLOB PATH &#39;$.embed_vector&#39;)) et; <br><br>1438 rows created.</pre><p><strong>Step 10:</strong> Generate a prompt using similarity search results</p><pre>SET SERVEROUTPUT ON;<br><br>VAR prompt CLOB;<br>VAR user_question CLOB;<br>VAR context CLOB;<br><br>SQL&gt; BEGIN<br><br>  -- initialize the concatenated string <br>  :context := &#39;&#39;;<br><br>  -- read this question from the user <br>  :user_question := &#39;what are vector indexes?&#39;;<br><br>  -- cursor to fetch chunks relevant to the user&#39;s query<br>  FOR rec IN (SELECT CHUNK_DATA<br>              FROM doc_chunks<br>              WHERE DOC_ID = 1<br>              ORDER BY vector_distance(CHUNK_EMBEDDING, vector_embedding(<br>                  ALL_MINILM_L12_V2 using :user_question as data), COSINE)<br>              FETCH EXACT FIRST 10 ROWS ONLY)<br>  LOOP<br>    -- concatenate each value to the string<br>    :context := :context || rec.CHUNK_DATA;<br>  END LOOP;<br>  <br>  -- concatenate strings and format it as an enhanced prompt to the LLM<br>  :prompt := &#39;Answer the following question using the supplied context <br>                assuming you are a subject matter expert. Question: &#39;<br>                || :user_question || &#39; Context: &#39; || :context;<br><br>  DBMS_OUTPUT.PUT_LINE(&#39;Generated prompt: &#39; || :prompt);<br>END;<br>/<br><br>Generated prompt: Answer the following question using the supplied context<br><br>assuming you are a subject matter expert. Question: what are vector indexes?<br>Context: vector index. The IVF index is a technique designed to enhance search<br>efficiency by narrowing ...<br><br>PL/SQL procedure successfully completed.</pre><p><strong>Step 11:</strong> Issue the Cohere GenAI call to generate the text</p><p><strong>Please Note:</strong> It is important to always consult the <a href="https://docs.cohere.com/reference/about">Cohere API documentation</a> before using it. This ensures that you have a clear understanding of how the API works and how to use it properly in your SQL or PL/SQL. This can help prevent issues and save time</p><pre>SQL&gt; DECLARE<br>  input CLOB;<br>  params CLOB;<br>  output CLOB;<br>  <br>BEGIN<br>  input := :prompt;<br>  params := &#39;{<br>    &quot;provider&quot; : &quot;cohere&quot;,<br>    &quot;credential_name&quot; : &quot;COHERE_CRED&quot;,<br>    &quot;url&quot; : &quot;https://api.cohere.com/v1/generate&quot;,<br>    &quot;model&quot; : &quot;command&quot;<br>  }&#39;;<br><br>  output := DBMS_VECTOR_CHAIN.UTL_TO_GENERATE_TEXT(input, json(params));<br>  DBMS_OUTPUT.PUT_LINE(output);<br>  IF output IS NOT NULL THEN<br>    DBMS_LOB.FREETEMPORARY(output);<br>  END IF;<br>EXCEPTION<br>  WHEN OTHERS THEN<br>    DBMS_OUTPUT.PUT_LINE(SQLERRM);<br>    DBMS_OUTPUT.PUT_LINE(SQLCODE);<br>END;<br>/<br><br>Vector indexes are a new category of specialized indexes designed for AI<br>workloads. They allow users to query data using semantics rather than keywords.<br>These indexes can efficiently search and organize data points in large datasets<br>and high-dimensional spaces using heuristic-based algorithms. These algorithms<br>aim to improve search efficiency by narrowing the search area through the use of<br>neighbor partitions or clusters.<br><br>PL/SQL procedure successfully completed.</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0982b497b1a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Oracle23ai Database — Work with Cohere Large Language Models (LLMs)]]></title>
            <link>https://medium.com/@karthikn.js/oracle23ai-database-work-with-cohere-large-language-models-llms-3d4696966147?source=rss-9f0aa679b51e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d4696966147</guid>
            <dc:creator><![CDATA[Karthikn]]></dc:creator>
            <pubDate>Tue, 24 Sep 2024 06:00:32 GMT</pubDate>
            <atom:updated>2024-09-24T06:01:29.955Z</atom:updated>
            <content:encoded><![CDATA[<p>We will examine the process of utilizing LLM-Powered Cohere APIs in this blog. These APIs provide functionalities that allow Vector Utility SQL Functions to give textual prompts to Large Language Models.</p><p>Below are some examples to illustrate this point.</p><ul><li>how to Generate Text String to Embedding.</li><li>how to Generate a textual answer, description, or summary based on the specified task in the prompt.</li><li>how to Summarize a given textual extract</li></ul><p><strong>Step 1 :</strong> <strong>Install Oracle23ai</strong></p><ul><li>Check out this link:<a href="https://www.oracle.com/in/database/free/get-started/">https://www.oracle.com/in/database/free/get-started/</a></li></ul><p><strong>Step 2 :</strong> Create a User and Grant privileges</p><pre>CONN sys/&lt;password&gt;@pdb AS sysdba;<br><br>CREATE USER vector IDENTIFIED BY VEctor123## <br><br>GRANT DB_DEVELOPER_ROLE, CREATE MINING MODEL TO vector;</pre><p><strong>Step 3:</strong> Grant connect privilege to allow connection to the host</p><pre>BEGIN<br>  DBMS_NETWORK_ACL_ADMIN.APPEND_HOST_ACE(<br>    host =&gt; &#39;*&#39;,<br>    ace =&gt; xs$ace_type(privilege_list =&gt; xs$name_list(&#39;connect&#39;),<br>                       principal_name =&gt; &#39;vector&#39;,<br>                       principal_type =&gt; xs_acl.ptype_db));<br>END;<br>/</pre><p><strong>Step 4 : </strong>Connect to Oracle Database as vector</p><pre>CONN vector/VEctor123##@pdb;</pre><p><strong>Step 5 : </strong>Set the HTTP proxy server, if configured</p><pre>SQL&gt; EXEC UTL_HTTP.SET_PROXY(&#39;&lt;proxy-hostname&gt;:&lt;proxy-port&gt;&#39;);<br><br>PL/SQL procedure successfully completed.</pre><p><strong>Step 6 : </strong>Set up your credentials for the Cohere REST provider</p><pre>SQL&gt; DECLARE<br>  jo json_object_t;<br>BEGIN<br>  jo := json_object_t();<br>  jo.put(&#39;access_token&#39;, &lt;access token&gt;);<br>  DBMS_VECTOR.CREATE_CREDENTIAL(<br>    credential_name   =&gt; &#39;COHERE_CRED&#39;,<br>    params            =&gt; json(jo.to_string));<br>END;<br>/<br>  2    3    4    5    6    7    8    9   10  <br>PL/SQL procedure successfully completed.</pre><p><strong>Please Note:</strong> It is important to always consult the <a href="https://docs.cohere.com/reference/about">Cohere API documentation</a> before using it. This ensures that you have a clear understanding of how the API works and how to use it properly in your SQL or PL/SQL. This can help prevent issues and save time.</p><p><strong>To generate the Embedding</strong></p><pre>SQL&gt; var params clob;<br><br>SQL&gt; BEGIN<br>:params := &#39;<br>             {<br>              &quot;provider&quot;: &quot;cohere&quot;,<br>              &quot;credential_name&quot;: &quot;COHERE_CRED&quot;,<br>              &quot;url&quot;: &quot;https://api.cohere.com/v1/embed&quot;,<br>              &quot;model&quot;: &quot;embed-english-v3.0&quot;,<br>              &quot;input_type&quot;: &quot;classification&quot;<br>             }&#39;;<br>END;<br>/<br>   <br>PL/SQL procedure successfully completed.<br><br>SQL&gt; select dbms_vector.utl_to_embedding(&#39;hello&#39;, json(:params)) from dual;<br><br>DBMS_VECTOR.UTL_TO_EMBEDDING(&#39;HELLO&#39;,JSON(:PARAMS))<br>--------------------------------------------------------------------------------<br>[1.58691406E-002,-8.21685791E-003,-4.9621582E-002,-7.05566406E-002,4.02927399E-0<br>04,-1.48162842E-002,-1.9317627E-002,1.98974609E-002,9.71221924E-003,4.19006348E-<br>002,-3.65600586E-002,-1.35302544E-005,6.34765625E-002,-3.54003906E-002,4.4433593<br>8E-002,-3.03344727E-002,3.62854004E-002,4.84008789E-002,5.10787964E-003,7.347106<br>93E-003,-2.07519531E-002,4.06494141E-002,-4.01306152E-002,3.53088379E-002,5.0689,<br>.....<br>.....<br><br>1 row selected.</pre><p><strong>To generate the BINARY embedding</strong></p><pre>SQL&gt; var params clob;<br><br>SQL&gt; BEGIN<br>:params := &#39;<br>             {<br>              &quot;provider&quot;: &quot;cohere&quot;,<br>              &quot;credential_name&quot;: &quot;COHERE_CRED&quot;,<br>              &quot;url&quot;: &quot;https://api.cohere.com/v1/embed&quot;,<br>              &quot;model&quot;: &quot;embed-english-v3.0&quot;,<br>              &quot;input_type&quot;: &quot;classification&quot;,<br>              &quot;embedding_types&quot;: [&quot;ubinary&quot;]<br>             }&#39;;<br>END;<br>/   <br><br>PL/SQL procedure successfully completed.<br><br>SQL&gt; SELECT TO_VECTOR(FROM_VECTOR(DBMS_VECTOR.UTL_TO_EMBEDDING(&#39;hello&#39;, JSON(:params))),*,BINARY);<br><br>TO_VECTOR(FROM_VECTOR(DBMS_VECTOR.UTL_TO_EMBEDDING(&#39;HELLO&#39;,JSON(:PARAMS))),*,BIN<br>--------------------------------------------------------------------------------<br>[137,202,245,195,211,132,169,63,43,22,12,93,112,93,85,208,145,31,92,245,99,222,1<br>21,63,1,161,200,24,1,30,206,233,208,2,113,27,119,78,123,192,132,115,187,146,58,1<br>36,40,63,221,52,68,241,53,88,20,99,85,248,114,177,100,248,100,158,94,53,61,97,18<br>2,129,14,64,173,236,107,109,37,195,173,49,128,121,204,183,158,55,139,10,205,65,4<br>0,53,243,247,134,63,125,133,55,230,129,66,165,103,102,46,251,164,213,139,227,225<br>,66,98,112,100,64,145,98,80,97,192,149,77,43,114,146,197]<br><br><br>1 row selected.</pre><p><strong>To generate the Text</strong></p><pre>SQL&gt; var params clob;<br><br>SQL&gt; BEGIN<br>:params := &#39;<br>             {<br>              &quot;provider&quot;: &quot;cohere&quot;,<br>              &quot;credential_name&quot;: &quot;COHERE_CRED&quot;,<br>              &quot;url&quot;: &quot;https://api.cohere.com/v1/generate&quot;,<br>              &quot;model&quot;: &quot;command&quot;,<br>             }&#39;;<br>END;<br>/   <br><br>PL/SQL procedure successfully completed.<br><br>SQL&gt; select dbms_vector_chain.utl_to_generate_text(&#39;What is Oracle Text?&#39;,json(:params)) from dual;<br><br>DBMS_VECTOR_CHAIN.UTL_TO_GENERATE_TEXT(&#39;WHATISORACLETEXT?&#39;,JSON(:PARAMS))<br>--------------------------------------------------------------------------------<br> Oracle Text is a powerful tool that enables organizations to search, gather, an<br>d analyze text data from a variety of sources, such as databases, documents, and<br> the web. It is a comprehensive text mining solution that integrates with the Or<br>acle Database to deliver high-performance text processing and analysis within an<br> enterprise grid computing environment.<br>.....<br>.....<br>These features and capabilities make Oracle Text a robust choice for organizatio<br>ns looking to search and analyze their text data efficiently and effectively. It<br> offers a comprehensive solution for knowledge management, content analytics, an<br>d improved decision-making in a variety of industries and use cases.<br><br><br>1 row selected.</pre><p><strong>To generate the Summary</strong></p><pre>SQL&gt; var params clob;<br><br>SQL&gt; BEGIN<br>:params := &#39;<br>             {<br>              &quot;provider&quot;: &quot;cohere&quot;,<br>              &quot;credential_name&quot;: &quot;COHERE_CRED&quot;,<br>              &quot;url&quot;: &quot;https://api.cohere.com/v1/summarize&quot;,<br>              &quot;model&quot;: &quot;command&quot;,<br>              &quot;format&quot;: &quot;bullets&quot;,<br>             }&#39;;<br>END;<br>/<br>  2    3    4    5    6    7    8    9   10   11  <br>PL/SQL procedure successfully completed.<br><br>SQL&gt; select dbms_vector_chain.utl_to_summary(&#39;Oracle Database guarantees that all three operations succeed or fail as a unit. For example, if a hardware failure prevents a statement in the transaction from executing, <br>then the other statements must be rolled back. Transactions set Oracle Database apart from a file system. If you perform an atomic operation that updates several files, and if the system fails halfway through, <br>then the files will not be consistent. In contrast, a transaction moves an Oracle database from one consistent state to another. The basic principle of a transaction is &quot;all or nothing&quot;: an atomic operation succeeds or fails as a whole.&#39;, <br>json(:params)) from dual;<br><br>DBMS_VECTOR_CHAIN.UTL_TO_SUMMARY(&#39;ORACLEDATABASEGUARANTEESTHATALLTHREEOPERATIONS<br>--------------------------------------------------------------------------------<br>- An Oracle Database transaction is a unit of work that moves a database from on<br>e consistent state to another.<br>- Transactions are atomic, meaning they succeed or fail as a whole, unlike file<br>systems that may leave files inconsistent if a system fails halfway through an o<br>peration.<br><br><br>1 row selected</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d4696966147" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Oracle23ai Database — HNSW Indexes]]></title>
            <link>https://medium.com/@karthikn.js/oracle23ai-database-hnsw-indexes-823243351cb1?source=rss-9f0aa679b51e------2</link>
            <guid isPermaLink="false">https://medium.com/p/823243351cb1</guid>
            <dc:creator><![CDATA[Karthikn]]></dc:creator>
            <pubDate>Thu, 12 Sep 2024 15:52:54 GMT</pubDate>
            <atom:updated>2024-09-12T15:52:54.730Z</atom:updated>
            <content:encoded><![CDATA[<h3>Oracle23ai Database — HNSW Indexes</h3><p>In a nutshell, <strong>HNSW</strong> creates a multi-layered graph structure where each layer is a simplified, navigable small world network. Before going further on HNSW, we should first explore the “<strong>Navigable Small World (NSW)”</strong> and a data structure called “<strong>Probability</strong> S<strong>kip Lists</strong>”, both of which make use of a graph-based data structure.</p><h3>Navigable Small World (NSW) Graphs</h3><p>The principle behind NSW is that every vector can be reached within a small number of “hops” from any other vector. After determining an entry point, the adjacent vectors are searched to see if any of them are closer than the current vector. The search moves to the closest of these neighboring vectors and repeats until there are no closer vectors.</p><p>Internally, the search algorithm employs two key lists: <strong>Candidates</strong>, a dynamically updated list of vectors that we encounter while traversing the graph, and <strong>Results</strong>, which contains the vectors closest to the query vector (vq) found thus far. As the search progresses, the algorithm navigates through the graph, continually refining the <strong>Candidates</strong> by exploring and evaluating vectors that might be closer than those in the Results. The process concludes once there are no vectors in the <strong>Candidates</strong> closer than the farthest in the <strong>Results</strong>, indicating a local minimum has been reached and the closest vectors to the query vector(vq) have been identified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*j7iEV1APXH45JkHXGJwaWQ.png" /></figure><p>In the following illustration, we are searching for the vector nearest to “A”, and start by looking at vector “0”. That vector is connected to three vectors, but the one that is closest to “A” is vector “1”. We then repeat the process from vector “1”, finding that vector “2” is closer than vector “1”, and finally that vector “3” is closer than vector “2”. The vectors connected to “3” are all further away from “A”, so we determine that “3” is the closest vector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*rlI2QpUOoS0jpBkyhe1zUw.png" /></figure><h3>Probability Skip Lists</h3><p>The Probability Skip List structure uses multiple layers of linked lists where the above layers are skipping more numbers than the lower ones. In the following illustration, you are trying to search for number 17. You start with the top layer and jump to the next element until you either find 17, reach the end of the list, or you find a number that is greater than 17. When you reach the end of a list or you find a number greater than 17, then you start in the previous layer from the latest number less than 17</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AxQMiz5ShlZF3a1J.png" /></figure><h3>Hierarchical Navigable Small World (HNSW)</h3><p>HNSW is a natural evolution of NSW, which borrows inspiration from hierarchical multi-layers from probability skip list structure.</p><p>Starting from the top layer, the search in one layer starts at the entry vector. Then for each vector, if there is a neighbor that is closer to the query vector(vq) than the current vector, it jumps to that neighbor. The algorithm keeps doing this until it finds a local minimum for the query vector (vq). When a local minimum is found in one layer, the search goes to the next layer by using the same vector in that new layer and the search continues in that layer. This process repeats itself until the local minimum of the bottom layer is found, which contains all the vectors. At this point, the search is transformed into an approximate similarity search using the NSW algorithm around that latest local minimum found to extract the top ‘k’ most similar vectors to your query vector (vq).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/0*NqApOFGIBn5UvqQF.png" /></figure><p>If we revisit our simple NSW example from above, we can see how the HNSW search process works. Looking for the nearest neighbor of vector “A”, we start by picking a vector on the top-most Layer 2 and navigating (as with NSW) to its nearest neighbor vector “1”. At this point, we go down a layer to Layer 1, and search to see if this layer has any closer neighbors, which we find as vector “2”. We finally go down to the bottom Layer 0, and find that vector “3” is closest:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/0*ex1Zc5aG0mzw3zP4" /></figure><h3>Parameters for HNSW</h3><ul><li>EFCONSTRUCTION — The maximum number of closest vector candidates considered at each step of the search during insertion</li><li>NEIGHBORS — Within the maximum number of connections permitted per vector</li></ul><p>If the combination of the above two thresholds is too high, then you may end up with a densely connected graph, which can slow down the search process. On the other hand, if the combination of those thresholds is too low, then the graph may become too sparse, which makes it challenging to find a path between certain vectors during the search.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=823243351cb1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Oracle23ai Database — IVF Flat Indexes]]></title>
            <link>https://medium.com/@karthikn.js/oracle23ai-database-ivf-flat-indexes-9e588b2652eb?source=rss-9f0aa679b51e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e588b2652eb</guid>
            <dc:creator><![CDATA[Karthikn]]></dc:creator>
            <pubDate>Thu, 12 Sep 2024 06:10:56 GMT</pubDate>
            <atom:updated>2024-09-12T06:10:56.022Z</atom:updated>
            <content:encoded><![CDATA[<h3>Oracle23ai Database — IVF Flat Indexes</h3><h4><strong>What are IVF Flat Vector Indexes?</strong></h4><p>The IVF Flat indexes are a type of vector index used in Oracle AI Vector Search Database to enhance search efficiency by narrowing the similarity search area through the use of <strong>neighbor partitions</strong> or <strong>clusters</strong>. This index type uses approximate nearest neighbor search (ANNS) to provide fast searches.</p><h4>How the IVF Flat Index Works</h4><ul><li>let’s consider a set of vectors represented in a two-dimensional space as the following points:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*X3n0gH9ObgAw3-lOBowWqQ.png" /><figcaption><em>A set of vectors represented as points in two dimensions</em></figcaption></figure><ul><li>The first step involves applying k-means clustering to the vectors to find cluster centroids. After computing the centroids, the next step is to assign each vector to its nearest centroid. This is accomplished by calculating the distance between the vector and each centroid and selecting the centroid with the smallest distance as the closest one</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*r5G2dAEKn2TZ6Guuz5GxOA.png" /><figcaption>After k-means clustering, we identify 5 clusters indicated by the black colored dot</figcaption></figure><ul><li>Mapping each point in space to the closest centroid based on proximity. By establishing this mapping, the space becomes divided into distinct regions surrounding each centroid. Each region represents a cluster of vectors that are close in semantic meaning.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*U22qvHnnZddlGWcHbrG5Zg.png" /><figcaption>Each vector falls within a specific neighbor partition or cluster associated with a centroid.</figcaption></figure><ul><li>Searching (vq) the IVF Flat index in the vector space</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*Tp9Xu9qKUndUrlu47zB_cw.png" /></figure><p>To find the approximate nearest neighbors (ANN) IVF Flat employs the following steps:</p><ol><li>Calculate the distance between the query vector (vq) and each centroid in the index.</li><li>Select the centroid with the smallest distance as the closest centroid to the query (#1 in this example).</li><li>Retrieve the vectors associated with the region corresponding to the closest centroid from the inverted index.</li><li>Compute the distances between the query vector (vq) and each of the vectors in the retrieved set.</li><li>Select the ‘K’ vectors with the smallest distances as the approximate nearest neighbors to the query vector.</li></ol><ul><li>How about search (vq) at the edge?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*aJ25eTARv7C3v9IOzz-chQ.png" /></figure><p>Just expand the search scope and improves the chances of finding the true nearest neighbors. This functionality is implemented through the ‘NEIGHBOR PARTITION PROBES’ parameter, which specifies the number of centroids to consider during the search. This adjustment allows for a trade-off between search speed and accuracy.</p><p>Higher numbers for this parameter will result in higher accuracy. Here, it’s set to 2 and the two identified partitions are partitions number 1 and 3 and The five nearest vectors to vq found in partitions number 1 and 3 are highlighted in the following diagram</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*Gfzcpc5TLfQPoDRjQPJJEg.png" /></figure><ul><li>Approximate Search Accuracy</li></ul><p>In this example, the approximate search accuracy is only 80% as it has retrieved only 4 out of 5 of the Exact search vectors’ result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*hWpmstFrJ0pvZrikVca83w.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e588b2652eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>