Skip to content

Commit

Permalink
[EDU-5569] [EDU-5571] feature: add Vector Search reference (#1355)
Browse files Browse the repository at this point in the history
* feature: create files with frontmatter EN-PT

* refactor: adjust store menu and add vector search item

* feature: add reference file EN/PT

* feature: add item in Release Notes - EN/PT

* refactor: add links to implementation table

* refactor: adjusting implementation table

* refactor: add link to sql reference

* refactor: add vector search item in edge sql ref EN/PT

* Apply suggestions from code review

Co-authored-by: Guilherme Afonso Oliveira  <[email protected]>

---------

Co-authored-by: Guilherme Afonso Oliveira <[email protected]>
  • Loading branch information
MarianaAguilera and guiafonso-ol authored Nov 14, 2024
1 parent b1656f3 commit fb13fd9
Show file tree
Hide file tree
Showing 8 changed files with 308 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ There are two ways to build a database through Edge SQL: using the Edge SQL REST
| Manage databases with REST API | [How to create an Edge SQL database](/en/documentation/products/guides/manage-databases-edge-sql/) |
| Create queries with REST API | [How to create and query data on Edge SQL](/en/documentation/products/guides/create-tables-edge-sql/) |
| Retrieve data from a database | [How to retrieve data from a database with Edge SQL and Edge Functions](/en/documentation/products/guides/edge-sql/retrieve-data-with-edge-functions/) |
| Get to know Edge SQL Vector Search | [Edge SQL Vector Search reference](/en/documentation/products/store/edge-sql/vector-search/) |

---

Expand Down Expand Up @@ -107,6 +108,12 @@ curl --location 'https://api.azion.com/v4/edge_sql/databases/{id_database}/query

---

## Vector Search

[Vector Search](/en/documentation/products/store/edge-sql/vector-search/) is an **Azion Edge SQL** feature that enables customers to implement semantic search engines. While traditional search models aim to find exact matches, such as keyword matches, vector search models use specialized algorithms to identify similar items based on their mathematical representations, or vector embeddings.

---

## Interacting with Edge SQL via Terminal

You can interact with Edge SQL directly from your terminal using [the edgesql-shell project](https://github.com/aziontech/edgesql-shell). This tool provides a command-line interface for executing SQL commands against your Edge SQL databases.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
---
title: Edge SQL Vector Search
description: Use Vector Search to implement semantic search engines, offering enhanced experiences and attending to advanced use cases.
meta_tags: vector search, Azion Edge SQL, AI-based applications, vector embeddings, SQLite
namespace: documentation_edge_sql_vector_search
permalink: /documentation/products/store/edge-sql/vector-search/
---

import Tag from 'primevue/tag';

<Tag severity="info" client:only="vue" value="Preview" />

**Vector Search** is an **Azion Edge SQL** feature that enables customers to implement semantic search engines. While traditional search models aim to find exact matches, such as keyword matches, vector search models use specialized algorithms to identify similar items based on their mathematical representations, or vector embeddings.

By using Vector Search, you can implement various use cases:

- Enhancing search systems and offering personalized recommendations by finding items with similar characteristics or based on users' preferences, such as related products in ecommerce or content in streaming platforms.
- Creating text embeddings to search for semantically similar text, where words or phrases are represented as vectors.
- Building AI-based applications, leveraging Natural Language Processing (NLP) for voice assistants and chatbots.

Distributed across the Azion global edge network, this feature enables more relevant search results, real-time recommendations, and insights, drastically reducing latency and improving user satisfaction. All of this while maintaining data locality and reducing dependence on the centralized database.

---

## Implementation

| Scope | Resource |
|---|---|
| Implement Vector Search | Guide explaining the basics of [implementing Vector Search](/en/documentation/products/guides/edge-sql-vector-search/) |
| Get to know Azion Edge SQL and its features | [Edge SQL reference](/en/documentation/products/store/edge-sql/) |

---

## Databases and storage

By leveraging Edge SQL, vector search databases are optimized to handle high-dimensional vector data at the edge. This enables fast, localized processing as well as reduced latency, allowing complex tasks for advanced data-intensive applications to run efficiently.

Edge SQL implements Main/Replicas, distributed within the Azion Edge Network, to enable ultra-low latency querying at the edge. This approach allows it to be accessed from any edge location, facilitating real-time processing and data analysis, and guaranteeing availability and fault tolerance. Edge SQL uses SQLite's dialect.

:::tip
The Azion Libraries provide tools and utilities to interact with Azion services both within and outside of the Azion Runtime environment. Explore the [Azion Libraries repository](https://github.com/aziontech/lib/tree/main) to know more about it.
:::

---

## Columns

To store vectors in a vector search database, you can add a column specifically for the vector data. Edge SQL Vector Seach supports embedding models, without dimension restrictions.

For example, using the `text-embedding-3-small` model and a `1536` dimension, this column should be declared to hold an array of 32-bit floating-point numbers as a binary large object (BLOB) type, as follows. The (3) in the example specifies the number of 32-bit floating-point (F32) elements in the vector, indicating a 3-dimensional vector:

```graphql
CREATE TABLE teams (
name TEXT,
year INT,
stats_embedding F32_BLOB(3)
);
```

Then, you can insert data in the table, including vector embeddings (in this example, representing team stats for the 2023 season):

```graphql
INSERT INTO teams (name, year, stats_embedding)
VALUES
(
'Red',
2023,
vector('[80, 30, 60]')
),
(
'Blue',
2023,
vector('[85, 25, 65]')
),
(
'Yellow',
2023,
vector('[78, 28, 62]')
),
(
'Green',
2023,
vector('[90, 20, 70]')
);
```

---

## Embeddings

Embeddings are numerical vector representations of complex data (like words or images) that capture essential characteristics, enabling similarity-based searches. In the example, given an embedding of [80, 30, 60] for a team, a query can retrieve other teams with similar embeddings, helping identify teams with comparable performance stats.

Using embeddings, you can query to find similar information between the teams. For example, teams with stats similar to 82 goals scored, 25 goals conceded, and 63% possession:

```graphql
SELECT name,
vector_extract(stats_embedding),
vector_distance_cos(stats_embedding, vector('[82, 25, 63]')) AS similarity
FROM teams
ORDER BY similarity ASC
LIMIT 3;
```

---

## Indexing

Considering Vector Search uses larger databases and datasets, it supports indexing through Approximate Nearest Neighbors (ANN), using SQL, wrapping the vector column into the `libsql_vector_idx` function.

```graphql
CREATE INDEX teams_idx ON teams ( libsql_vector_idx(embedding) );
```

To adequately use the index, you can modify your query to guarantee the index is consulted. Using the index is not automatic, since it is internally represented as a different table. For the previous example query, we can modify it slightly to make sure the index is consulted:

```graphql
SELECT
name,
year,
similarity
FROM
teams
JOIN
vector_top_k('teams_idx', '[4,5,6]', 3)
ON
teams.rowid = id
WHERE
year >= 2023;
```
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,16 @@ permalink: /documentation/products/release-notes/
---
import Tag from 'primevue/tag'

## October 31, 2024

### Edge SQL Vector Search

**Vector Search** is a new **Azion Edge SQL** feature that enables customers to implement semantic search engines for various use cases, resulting in more relevant search results, real-time recommendations, and insights while drastically reducing latency and improving user satisfaction.

Get to know Edge SQL Vector Search by reading the [documentation](/en/documentation/products/store/edge-sql/vector-search/).

---

## October 30, 2024

### Real-Time Events
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ Existem duas maneiras de construir um banco de dados através do Edge SQL: usand
| Gerenciar bancos de dados com API REST | [Como gerenciar um banco de dados no Edge SQL](/pt-br/documentacao/produtos/guias/gerenciar-bancos-dados-edge-sql/) |
| Criar queries com API REST | [Como criar e consultar dados no Edge SQL](/pt-br/documentacao/produtos/guias/criar-tabelas-edge-sql/) |
| Ler dados de um banco de dados com uma edge function | [Como interagir com o Azion Edge SQL através do Edge Functions](/pt-br/documentacao/produtos/guides/edge-sql/listando-dados-edge-functions-edge-sql/) |
| Conhecer o Vector Search do Edge SQL | [Referência do Vector Search do Edge SQL](/pt-br/documentacao/produtos/store/edge-sql/vector-search/) |

---

Expand Down Expand Up @@ -109,6 +110,12 @@ curl --location 'https://api.azion.com/v4/edge_sql/databases/{id_database}/query

---

## Vector Search

[Vector Search](/pt-br/documentacao/produtos/store/edge-sql/vector-search/) é um recurso do **Edge SQL da Azion** que permite aos clientes implementar mecanismos de busca semântica. Enquanto os modelos de busca tradicionais visam encontrar correspondências exatas, como correspondências de palavras-chave, os modelos de busca vetorial usam algoritmos especializados para identificar itens semelhantes com base em suas representações matemáticas, ou embeddings vetoriais.

---

## Interagindo com o Edge SQL via terminal

Você pode interagir com o Edge SQL diretamente do seu terminal usando [o projeto edgesql-shell](https://github.com/aziontech/edgesql-shell). Esta ferramenta fornece uma interface de linha de comando para executar comandos SQL em seus bancos de dados Edge SQL.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
---
title: Vector Search do Edge SQL
description: Use o Vector Search para implementar mecanismos de busca semântica, oferecendo experiências aprimoradas e atendendo a casos de uso avançados.
meta_tags: vector search, busca vetorial, Azion Edge SQL, aplicações baseadas em IA, vector embeddings, SQLite
namespace: documentation_edge_sql_vector_search
permalink: /documentacao/produtos/store/edge-sql/vector-search/
---

import Tag from 'primevue/tag';

<Tag severity="info" client:only="vue" value="Preview" />

**Vector Search** é um recurso do **Edge SQL da Azion** que permite aos clientes implementar mecanismos de busca semântica. Enquanto os modelos de busca tradicionais visam encontrar correspondências exatas, como correspondências de palavras-chave, os modelos de busca vetorial usam algoritmos especializados para identificar itens semelhantes com base em suas representações matemáticas, ou embeddings vetoriais.

Ao usar o Vector Search, você pode implementar vários casos de uso:

- Melhorar sistemas de busca e oferecer recomendações personalizadas, encontrando itens com características semelhantes ou com base nas preferências dos usuários, como produtos relacionados em e-commerce ou conteúdo em plataformas de streaming.
- Criar embeddings de texto para buscar texto semanticamente semelhante, onde palavras ou frases são representadas como vetores.
- Construir aplicações baseadas em IA, aproveitando o Processamento de Linguagem Natural (NLP) para assistentes de voz e chatbots.

Distribuído pela rede global de edge da Azion, esse recurso permite resultados de busca mais relevantes, recomendações em tempo real e insights, reduzindo drasticamente a latência e melhorando a satisfação do usuário. Tudo isso enquanto mantém a localidade dos dados e reduz a dependência do banco de dados centralizado.

---

## Implementação

| Escopo | Recurso |
|---|---|
| Implemente o Vector Search| Guia explicando os fundamentos da [implementação do Vector Search](/pt-br/documentacao/produtos/guias/edge-sql-vector-search/) |
| Conheça o Edge SQL da Azion e suas funcionalidades | [Referência do Edge SQL](/pt-br/documentacao/produtos/store/edge-sql/) |

---

## Bancos de dados e armazenamento

Ao aproveitar o Edge SQL, os bancos de dados de busca vetorial são otimizados para lidar com dados vetoriais de alta dimensão no edge. Isso permite processamento rápido e localizado, bem como redução de latência, permitindo que tarefas complexas para aplicações avançadas e intensivas em dados sejam executadas de forma eficiente.

O Edge SQL implementa Main/Replicas, distribuídos dentro da Edge Network da Azion, para permitir consultas de ultra-baixa latência no edge. Essa abordagem permite que seja acessado de qualquer edge location, facilitando o processamento em tempo real e a análise de dados, garantindo disponibilidade e tolerância a falhas. O Edge SQL usa o dialeto do SQLite.

:::tip
As Azion Libraries fornecem ferramentas para interagir com os serviços da Azion tanto dentro quanto fora do ambiente de Runtime da Azion. Explore o [repositório das Azion Libraries](https://github.com/aziontech/lib/tree/main) para saber mais.
:::

---

## Colunas

Para armazenar vetores em um banco de dados de busca vetorial, você pode adicionar uma coluna especificamente para os dados vetoriais. O Vector Search do Edge SQL suporta modelos de embedding, sem restrições de dimensão.

Por exemplo, usando o modelo `text-embedding-3-small` e uma dimensão de `1536`, essa coluna deve ser declarada para conter um array de números de ponto flutuante de 32 bits como um tipo de objeto binário grande (BLOB). O (3) no exemplo especifica o número de elementos de ponto flutuante de 32 bits (F32) no vetor, indicando um vetor de 3 dimensões:

```graphql
CREATE TABLE teams (
name TEXT,
year INT,
stats_embedding F32_BLOB(3)
);
```

Em seguida, você pode inserir dados na tabela, incluindo embeddings vetoriais (neste exemplo, representando as estatísticas da equipe para a temporada de 2023):

```graphql
INSERT INTO teams (name, year, stats_embedding)
VALUES
(
'Red',
2023,
vector('[80, 30, 60]')
),
(
'Blue',
2023,
vector('[85, 25, 65]')
),
(
'Yellow',
2023,
vector('[78, 28, 62]')
),
(
'Green',
2023,
vector('[90, 20, 70]')
);
```

---

## Embeddings

Embeddings são representações vetoriais numéricas de dados complexos (como palavras ou imagens) que capturam características essenciais, permitindo buscas baseadas em similaridade. No exemplo, dado um embedding de [80, 30, 60] para uma equipe, uma consulta pode recuperar outras equipes com embeddings semelhantes, ajudando a identificar equipes com estatísticas de desempenho comparáveis.

Usando embeddings, você pode consultar para encontrar informações semelhantes entre as equipes. Por exemplo, equipes com estatísticas semelhantes a 82 gols marcados, 25 gols sofridos e 63% de posse de bola:

```graphql
SELECT name,
vector_extract(stats_embedding),
vector_distance_cos(stats_embedding, vector('[82, 25, 63]')) AS similarity
FROM teams
ORDER BY similarity ASC
LIMIT 3;
```

---

## Indexação

Considerando que o Vector Search usa bancos de dados e conjuntos de dados maiores, ele suporta indexação através de Vizinhos Aproximados Mais Próximos (ANN), usando SQL, envolvendo a coluna vetorial na função `libsql_vector_idx`.

```graphql
CREATE INDEX teams_idx ON teams ( libsql_vector_idx(embedding) );
```

Para usar adequadamente o índice, você pode modificar sua consulta para garantir que o índice seja consultado. Usar o índice não é automático, uma vez que ele é representado internamente como uma tabela diferente. Para a consulta do exemplo anterior, podemos modificá-la ligeiramente para garantir que o índice seja consultado:

```graphql
SELECT
name,
year,
similarity
FROM
teams
JOIN
vector_top_k('teams_idx', '[4,5,6]', 3)
ON
teams.rowid = id
WHERE
year >= 2023;
```

Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,16 @@ permalink: /documentacao/produtos/release-notes/
---
import Tag from 'primevue/tag'

## 31 de outubro, 2024

### Vector Search do Edge SQL

**Vector Search** é um novo recurso do Edge SQL da Azion que permite aos clientes implementar motores de busca semântica para diversos casos de uso, resultando em resultados de busca mais relevantes, recomendações em tempo real e insights, ao mesmo tempo em que reduz drasticamente a latência e melhora a satisfação do usuário.

Conheça o Vector Search do Edge SQL na [documentação](/pt-br/documentacao/produtos/store/edge-sql/vector-search/).

---

## 30 de outubro, 2024

### Real-Time Events
Expand Down
13 changes: 7 additions & 6 deletions src/i18n/en/nav.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,13 @@ export default [
{ text: 'Rules Engine', header: true, anchor: true, type: 'learn', key: 'reference/rulesEngineedgeApplication', slug: '/documentation/products/build/edge-application/rules-engine/' },
]
},
{
text: 'Store', header: true, type: 'learn', key: 'storeRef', items: [
{ text: 'Edge Storage', header: true, anchor: true, type: 'learn', key: 'reference/storage', slug: '/documentation/products/store/edge-storage/' },
{ text: 'Edge SQL', header: true, anchor: true, type: 'learn', key: 'reference/sql', slug: '/documentation/products/store/edge-sql/' },
{ text: 'Vector Search', header: true, anchor: true, type: 'learn', key: 'reference/vector-search', slug: '/documentation/products/store/edge-sql/vector-search/' },
]
},
{
text: 'Secure', header: true, type: 'learn', key: 'secureRef', items: [
{ text: 'Edge Firewall', header: true, anchor: true, type: 'learn', key: 'reference/edgeFirewall', slug: '/documentation/products/secure/edge-firewall/' },
Expand Down Expand Up @@ -126,12 +133,6 @@ export default [

]
},
{
text: 'Store', header: true, type: 'learn', key: 'storeRef', items: [
{ text: 'Edge Storage', header: true, anchor: true, type: 'learn', key: 'reference/storage', slug: '/documentation/products/store/edge-storage/' },
{ text: 'Edge SQL', header: true, anchor: true, type: 'learn', key: 'reference/sql', slug: '/documentation/products/store/edge-sql/' },
]
},
{
text: 'Marketplace', header: true, type: 'learn', key: 'mktpRef', items: [
{ text: 'Marketplace', header: true, anchor: true, type: 'learn', key: 'mktp', slug: '/documentation/products/marketplace/' },
Expand Down
14 changes: 8 additions & 6 deletions src/i18n/pt-br/nav.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,14 @@ export default NavDictionary([
{ text: 'Origins', key: 'reference/origins', slug: '/documentacao/produtos/edge-application/origins/' },
{ text: 'Real-Time Purge', key: 'reference/realTimePurge', slug: '/documentacao/produtos/edge-application/real-time-purge/' },
{ text: 'Rules Engine', key: 'reference/rulesEngineedgeApplication', slug: '/documentacao/produtos/edge-application/rules-engine/' },


{
text: 'Store', key: 'storeRef'
},
{ text: 'Edge Storage', key: 'reference/storage', slug: '/documentacao/produtos/store/edge-storage/' },
{ text: 'Edge SQL', key: 'reference/sql', slug: '/documentacao/produtos/store/edge-sql/' },
{ text: 'Vector Search', key: 'reference/vector-search', slug: '/documentacao/produtos/store/edge-sql/vector-search/' },

{
text: 'Secure', key: 'secureRef'
},
Expand Down Expand Up @@ -125,11 +132,6 @@ export default NavDictionary([
{ text: 'Real-Time Metrics', key: 'reference/realTimeMetrics', slug: '/documentacao/produtos/real-time-metrics/' },
{ text: 'Real-Time Metrics Histórico', key: 'reference/historicalRealTimeMetrics', slug: '/documentacao/produtos/real-time-metrics-historico/' },


{ text: 'Edge Storage', key: 'reference/storage', slug: '/documentacao/produtos/store/edge-storage/' },
{ text: 'Edge SQL', key: 'reference/sql', slug: '/documentacao/produtos/store/edge-sql/' },


{ text: 'Marketplace', key: 'mktpRef' },
{ text: 'Marketplace', key: 'mktp', slug: '/documentacao/produtos/marketplace/' },
{ text: 'Permissões', key: 'mktp/permissions', slug: '/documentacao/produtos/guias/permissoes-marketplace/' },
Expand Down

0 comments on commit fb13fd9

Please sign in to comment.