How Vector Databases Work: A Hands-On Tutorial!
Tags: database, ai, datascience, dataengineering
Published: 2023-11-30 09:59:50

At the heart of this revolution lies the concept of vector databases, a groundbreaking development that is reshaping how we handle complex data. Unlike traditional relational databases, these are uniquely equipped to manage and process high-dimensional vector data — which is intrinsic to many AI and machine learning applications. As we delve deeper into the era of advanced AI vector databases are emerging as critical tools, offering unparalleled efficiency and accuracy in handling the vast, intricate datasets generated by generative AI models. 

This article aims to explore the pivotal role of vector databases in the world of [generative AI](https://www.singlestore.com/solutions/gen-ai/), highlighting their functionality, how they work, use cases and a hands-on tutorial.

## What is a vector database?
A vector database is a kind of database that is designed to store, index and retrieve data points with multiple dimensions, which are commonly referred to as vectors. Unlike databases that handle data (like numbers and strings) organized in tables, [vector databases](https://www.singlestore.com/built-in-vector-database/) are specifically designed for managing data represented in multi-dimensional vector space. This makes them highly suitable for AI and machine learning applications, where data often takes the form of vectors like image embeddings, text embeddings or other types of feature vectors. 

These databases utilize indexing and search algorithms to conduct similarity searches, enabling them to rapidly identify the most similar vectors within a dataset. This capability is crucial for tasks like recommendation systems, image and voice recognition — as well as natural language processing, since efficiently understanding and processing high dimensional data plays a vital role. Consequently, vector databases represent an advancement in database technology tailored to meet the requirements of AI applications that rely heavily on vast amounts of data.

**Vector embeddings**
![vector embeddings](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lh5r4ijajeed9iktg121.png)

When we talk about vector databases, we should definitely know what vector embeddings are — how  data eventually gets stored in a vector database. [Vector embeddings](https://www.singlestore.com/blog/implement-vector-embeddings-on-json-data/) serve as numerical codes that encapsulate the key characteristics of objects; for example, songs in a music streaming app. By analyzing and extracting crucial features (like tempo and genre), each song is converted into a vector embedding through an embedding model. This process ensures that songs with similar attributes have similar vector codes. A vector database stores these embeddings and, upon a query, compares these vectors to find and recommend songs with the closest matching features — facilitating an efficient and relevant search experience for the user.

## How Does a Vector Database Work?
![how vector database works](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tyg0ah0u3x3rcdqcydym.png)

When a user query is initiated, various types of raw data including  images, documents, videos and audio. All of this, which can be either unstructured or structured, are first processed through an embedding model. This model is often a complex neural network, translating  data into high-dimensional numerical vectors and effectively encoding the data's characteristics into vector embeddings — which are then stored into a vector database like SingleStoreDB. 

When retrieval is required, the vector database performs operations (like similarity searches) to find and retrieve the vectors most similar to the query, efficiently handling complex queries and delivering relevant results to the user. This entire process enables the rapid and accurate management of vast and varied data types in applications that require high-speed search and retrieval functions.

## How Does a Vector Database Differs from a Traditional Database?
![traditional db vs vector db](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oqht7dlrdwis189j188m.png)

Vector databases represent a significant departure from traditional databases in their approach to data organization and retrieval. Traditional databases are structured to handle discrete, scalar data types like numbers and strings, organizing them in rows and columns. This structure is ideal for transactional data but less efficient for the complex, high-dimensional data typically used in AI and machine learning. In contrast, vector databases are designed to store and manage [vector data](https://docs.singlestore.com/cloud/developer-resources/functional-extensions/working-with-vector-data/) —  arrays of numbers that represent points in a multi-dimensional space. 

This makes them inherently suited for tasks involving similarity search where the goal is to find the closest data points in a high-dimensional space, a common requirement in AI applications like image and voice recognition, recommendation systems and natural language processing. 

By leveraging indexing and search algorithms optimized for high-dimensional vector spaces, vector databases offer a more efficient and effective way to handle the kind of data that is increasingly prevalent in the age of advanced AI and machine learning.

## Vector Database Use Cases
Vector databases play a vital role in recommendation systems for businesses. For example, they can recommend items to a user depending on their browsing or buying behavior. They shine well even in fraud detection systems where they can detect anomalous patterns by comparing transaction embeddings against known profiles of fraudulent activity, thus enabling real-time fraud detection. Face recognition is an additional use case where vector databases store facial feature embeddings and help in security and surveillance. 

They can even help organizations with customer support by responding to the similar queries with pre-determined or  little varied responses.  Market research is another area where vector databases do well by analyzing customer feedback and social media posts, converting them into text embeddings to do sentiment analysis and trend spotting — gaining even more business insights. 

## SingleStoreDB as a Vector Database
The robust [vector database capabilities of SingleStoreDB](https://docs.singlestore.com/cloud/developer-resources/functional-extensions/working-with-vector-data/) are tailored to seamlessly serve AI-driven applications, chatbots, image recognition systems and more. With SingleStoreDB, the necessity for maintaining a dedicated vector database for your vector-intensive workloads becomes obsolete.

![singlestore as a vector database](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t5s4kwx59ibewfao70fy.png)

Diverging from conventional vector database approaches, SingleStoreDB takes a novel approach by housing vector data within relational tables alongside diverse data types. This innovative amalgamation empowers you to effortlessly access comprehensive metadata and additional attributes pertaining to your vector data, all while leveraging the extensive querying prowess of SQL.

SingleStoreDB has been meticulously architected with a scalable framework, ensuring unfaltering support for your burgeoning data requirements. Say goodbye to limitations and embrace a solution that grows in tandem with your data demands.

## Vector Database Tutorial Using SingleStoreDB
#### Prerequisites
- Sign up for your [free SingleStoreDB Cloud](https://www.singlestore.com/cloud-trial/?utm_medium=referral&utm_source=pavan&utm_term=devto&utm_content=vectrdbtut) trial.  We will use SingleStore as our vector database.
- [Postman account](https://www.postman.com) to create embeddings
- [OpenAI account](https://auth0.openai.com/u/signup/identifier?state=hKFo2SBXdHpVcVNOQ1JFa2NfcW5wemw4ZUVNRHQ3U3FhX2ticqFur3VuaXZlcnNhbC1sb2dpbqN0aWTZIDZxZUZ3eXJlWFJEb2pfVmxZNkJscGVYam1VeUQ4emxWo2NpZNkgRFJpdnNubTJNdTQyVDNLT3BxZHR3QjNOWXZpSFl6d0Q) to get our OpenAI API key

Once you sign in to your OpenAI account, go to the API tab as shown here. 
![openAI Account](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ndqycih2a92q51v3qqv3.png)

Next, go to the embeddings tab.
![embeddings tab](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0v3sk2tlh1a3t1awreko.png)

We are going to start off with API requests for embeddings. To do that, we will need to go to the API References page. Move to the ‘Embeddings’ tab under the [API References](https://platform.openai.com/docs/api-reference) page to see how to create embeddings.

![create embeddings](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t6ueubnznpkhtlklzsxf.png)

Now, let’s create API requests for our embeddings. For this we need a tool like [Postman](https://www.postman.com/).
You can sign up and create a workspace in your [Postman account](https://www.postman.com/).
![postman account](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qob0gdd3ek45l9bgjms4.png)

Now, get our API url (https://api.openai.com/v1/embeddings) and paste it in the Postman URL section, authorizing it using your [OpenAI API Key](https://platform.openai.com/api-keys). 

![openai keys](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oo0kbdqe5wm3vo393txa.png)

It is time to create our first embedding. We just need a model and the input parameters as shown in the OpenAI document page.
![request body](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ey569wucpildotzfd302.png)

For the model, we will be using “text-embedding-ada-002” and any text for the input.
![embedding model](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jlt15y92m5cbptk9kzkm.png)

Let’s do this. Head over to the Postman dashboard and create a ‘body’ request. Under the body, select ‘raw’ and then select ‘JSON’ to pass a JSON object. 
![JSON Object](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0kt0t6ezz2efbxoaqqop.png)

Mention the model and input 
![model input](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1fh9j64av4cun8s8rcr4.png)

Send the post request to OpenAI. You should see a similar response as shown here.

![hello world embedding](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5p5wwjcbf5glutu3e9d9.png)

The numbers you see are the vectors for the embedding.

To store these vector embeddings, you need a robust database — that is where SingleStoreDB shines. Let’s create a free [SingleStoreDB Cloud account](https://www.singlestore.com/cloud-trial/?utm_medium=referral&utm_source=pavan&utm_term=devto&utm_content=vectrdbtut). 

![singlestoredb account](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t7ls837xglqabqzvejkg.png)

Next, create a workspace as shown here. 
![singlestore workspace](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/twp854yyeyj037bd83jr.png)

You can see your created workspace and sample/default database attached.

![openai vector database](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pldupi0z57583p4o55ao.png)

Let’s create a database
![create database](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/skpkrad0dq7hkx80ypht.png)

The newly created database can be seen in the dashboard.

![vector db group](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/39b0exqotrja4vc4lm5y.png)

You can go inside this database to see the contents. In this case since we haven’t fed any data yet, you won’t see anything. 
![database content](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/57lmd3vll8j6z965hzs9.png)

Let’s create some tables in our database. Head over to the ‘SQL Editor’ as shown. You canrun some simple SQL commands to create tables.
![SQL Editor](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/859ftnufx737c0d3btkp.png)

Make sure to select the database under the ‘Select Database’ tab. Select the database that we created a while back.
![openai database](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s0ytyykrta82h82dvdqd.png)

Write a simple SQL query to create a table and data type.
![vector blob](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6urbwo71dlosvah3gsz2.png)

Now, let’s insert vector data into this database. This is where we are going to feed our embedding data we received from Postman.

Head back to the SQL Editor and write the following SQL Query.
![vector table](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ole0r7tvpmwpll3tdze8.png)

We will be using values with reference to our ‘Hello World’ input from postman.

Insert the huge block of numbers we received from Postman inside the JSON_ARRAY_PACK.
![hello world embeddings](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/389s5pmx5e2z6npsl40p.png)

[Copy these numbers from Postman]

Paste the huge block of numbers into your values and run the command.
![vectr embeddings](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5swc1bubf87rkdqf49f9.png)

You can see the results being fed into our database.
![helo wrld embeddings](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rjf9mfpkjozh6p95xb7q.png)

That’s it! This is how you can create different embeddings using Postman from different inputs and add the generated vector embeddings to your newly created database.

![openai vectors](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pu80tn0flaps39cu6dsf.png)

Use the same approach as earlier to store them under our database.

Add your own inputs and content to convert them into vectors. As you can see here, we have added different inputs and stored the generated vector embeddings into our database.

![convert embeddings](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1jw9h5w5iw7dbqdhguor.png)

Let’s do some experimentation now by searching some specific terms and retrieving relevant data from our database.

Let’s go back to the Postman dashboard and create an embedding for the term ‘OpenAI’.
![prompt token](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y1m2e6bf3k1ia5e9zo6f.png)

Next, we will perform a search in the database against the existing embeddings. This should give us results with the list of closest similarity being at the top. 

Let’s head over to the SQL editor and run this query as shown.
![openai sql workspace](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dgla9s2s4qx80smkc1x4.png)

Paste the embedding (huge block of numbers) inside JSON_ARRAY_PACK and run the command.
![all embeddings](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/50iw0urm0uuvb6tph29a.png)

In the preceding above, you can see the similarity scores and rankings for the keyword ‘OpenAI’.

Similarly, you can see similarity scores for any keywords. This way, SingleStoreDB can be used as an efficient vector database for your business.
 
SingleStoreDB emerges not only as an efficient vector database but also as a powerful platform for real-time analytics. Its ability to handle vector data efficiently enables complex operations like similarity search and machine learning applications, making it a go-to choice for modern data-driven scenarios. Simultaneously, SingleStoreDB's real-time analytics capabilities provide an invaluable resource for businesses looking to make data-driven decisions swiftly and accurately. 

By integrating these two functionalities, SingleStore stands out as a comprehensive solution that caters to the evolving needs of data storage and analysis. Organizations leveraging SingleStoreDB to see significant improvements in both the management of vector data, and the speed and accuracy of their analytical insights.

Try [SingleStoreDB as a vector database](https://www.singlestore.com/cloud-trial/?utm_medium=referral&utm_source=pavan&utm_term=devto&utm_content=vectrdbtut) today & claim your $600 worth cloud resources.