Stop Thinking, Just Do!

Sungsoo Kim's Blog

What is a Vector Database?

tagsTags

1 August 2023


Article Source


What is a Vector Database?

We’re in the midst of the AI revolution. It’s upending any industry it touches, promising great innovations - but it also introduces new challenges. Efficient data processing has become more crucial than ever for applications that involve large language models, generative AI, and semantic search.

All of these new applications rely on vector embeddings, a type of data representation that carries within it semantic information that’s critical for the AI to gain understanding and maintain a long-term memory they can draw upon when executing complex tasks.

Embeddings are generated by AI models (such as Large Language Models) and have a large number of attributes or features, making their representation challenging to manage. In the context of AI and machine learning, these features represent different dimensions of the data that are essential for understanding patterns, relationships, and underlying structures.

That is why we need a specialized database designed specifically for handling this type of data. Vector databases like Pinecone fulfill this requirement by offering optimized storage and querying capabilities for embeddings. Vector databases have the capabilities of a traditional database that are absent in standalone vector indexes and the specialization of dealing with vector embeddings, which traditional scalar-based databases lack.

The challenge of working with vector embeddings is that traditional scalar-based databases can’t keep up with the complexity and scale of such data, making it difficult to extract insights and perform real-time analysis. That’s where vector databases come into play – they are intentionally designed to handle this type of data and offer the performance, scalability, and flexibility you need to make the most out of your data.

With a vector database, we can add advanced features to our AIs, like semantic information retrieval, long-term memory, and more. The diagram below gives us a better understanding of the role of vector databases in this type of application:


우리는 AI 혁명의 중간에 있습니다. 이는 그것이 접촉하는 모든 산업을 혼란스럽게 만들며, 혁신적인 발전을 약속하지만 동시에 새로운 도전도 가져옵니다. 대규모 언어 모델, 생성적 AI, 의미 검색을 포함하는 애플리케이션에 대해 효율적인 데이터 처리는 이전보다 더 중요해졌습니다.

이러한 새로운 애플리케이션들은 벡터 임베딩에 의존하며, 이는 AI가 이해하는 데 필수적인 의미적 정보를 내포하고 있으며 복잡한 작업을 실행할 때 참고할 수 있는 오랜 기억을 유지하는 데에 중요합니다.

임베딩은 AI 모델(예: 대형 언어 모델)에 의해 생성되며, 많은 속성이나 특성을 가지고 있어 그들의 표현을 관리하기 어렵게 만듭니다. AI와 기계 학습의 맥락에서 이러한 특성은 데이터의 다양한 차원을 나타내며, 패턴, 관계 및 기본 구조를 이해하는 데에 중요합니다.

그래서 이러한 유형의 데이터를 처리하기 위해 특화된 데이터베이스가 필요합니다. Pinecone과 같은 벡터 데이터베이스는 이러한 요구 사항을 충족시키기 위해 최적화된 저장 및 쿼리 기능을 제공합니다. 벡터 데이터베이스는 독립적인 벡터 인덱스에서는 볼 수 없는 전통적인 데이터베이스의 기능과 벡터 임베딩 처리에 대한 특수화를 갖추고 있으며, 전통적인 스칼라 기반 데이터베이스에서 부족한 것입니다.

벡터 임베딩을 다루는 도전은 전통적인 스칼라 기반 데이터베이스가 이러한 데이터의 복잡성과 규모에 대응하기 어렵다는 것입니다. 이로 인해 통찰력을 추출하고 실시간 분석을 수행하는 것이 어려워집니다. 이 때 벡터 데이터베이스가 필요한데, 이러한 유형의 데이터를 처리하도록 특별히 설계되어 성능, 확장성 및 유연성을 제공합니다.

벡터 데이터베이스를 사용하면 의미적 정보 검색, 오랜 기억 등과 같은 고급 기능을 AI에 추가할 수 있습니다. 아래 다이어그램은 벡터 데이터베이스의 역할을 이해하는 데 도움을 줍니다.

Vector
Database

Let’s break this down:

  1. First, we use the embedding model to create vector embeddings for the content we want to index.

  2. The vector embedding is inserted into the vector database, with some reference to the original content the embedding was created from.

  3. When the application issues a query, we use the same embedding model to create embeddings for the query, and use those embeddings to query the database for similar vector embeddings. And as mentioned before, those similar embeddings are associated with the original content that was used to create them.


이를 자세히 살펴보겠습니다:

  1. 먼저, 우리는 색인하려는 내용에 대한 벡터 임베딩을 생성하기 위해 임베딩 모델을 사용합니다.
  2. 벡터 임베딩은 원래의 내용과 어떤 참조와 함께 벡터 데이터베이스에 삽입됩니다. 이 참조는 임베딩이 생성된 원본 내용과 관련된 정보를 제공합니다.
  3. 애플리케이션이 쿼리를 발행하면, 우리는 같은 임베딩 모델을 사용하여 쿼리에 대한 임베딩을 생성하고, 이 임베딩을 사용하여 데이터베이스에서 유사한 벡터 임베딩을 조회합니다. 그리고 앞서 언급한대로, 이러한 유사한 임베딩은 그들이 생성된 원본 내용과 연결됩니다.

What’s the difference between a vector index and a vector database?

Standalone vector indices like FAISS (Facebook AI Similarity Search) can significantly improve search and retrieval of vector embeddings, but they lack capabilities that exist in any database. Vector databases, on the other hand, are purpose-built to manage vector embeddings, providing several advantages over using standalone vector indices:

  1. Data management: Vector databases offer well-known and easy-to-use features for data storage, like inserting, deleting, and updating data. This makes managing and maintaining vector data easier than using a standalone vector index like FAISS, which requires additional work to integrate with a storage solution.

  2. Metadata storage and filtering: Vector databases can store metadata associated with each vector entry. Users can then query the database using additional metadata filters for finer-grained queries.

  3. Scalability: Vector databases are designed to scale with growing data volumes and user demands, providing better support for distributed and parallel processing. Standalone vector indices may require custom solutions to achieve similar levels of scalability (such as deploying and managing them on Kubernetes clusters or other similar systems).

  4. Real-time updates: Vector databases often support real-time data updates, allowing for dynamic changes to the data, whereas standalone vector indexes may require a full re-indexing process to incorporate new data, which can be time-consuming and computationally expensive.

  5. Backups and collections: Vector databases handle the routine operation of backing up all the data stored in the database. Pinecone also allows users to selectively choose specific indexes that can be backed up in the form of “collections,” which store the data in that index for later use.

  6. Ecosystem integration: Vector databases can more easily integrate with other components of a data processing ecosystem, such as ETL pipelines (like Spark), analytics tools (like Tableau and Segment), and visualization platforms (like Grafana) – streamlining the data management workflow. It also enables easy integration with other AI related tools like LangChain, LlamaIndex and ChatGPT’s Plugins.

  7. Data security and access control: Vector databases typically offer built-in data security features and access control mechanisms to protect sensitive information, which may not be available in standalone vector index solutions.

In short, a vector database provides a superior solution for handling vector embeddings by addressing the limitations of standalone vector indices, such as scalability challenges, cumbersome integration processes, and the absence of real-time updates and built-in security measures, ensuring a more effective and streamlined data management experience.


Standalone vector indices like FAISS (Facebook AI Similarity Search)는 벡터 임베딩의 검색과 검색 성능을 크게 향상시킬 수 있지만, 일반적인 데이터베이스에 존재하는 기능들은 갖추지 못합니다. 반면에 벡터 데이터베이스는 벡터 임베딩을 관리하는 데 특화되어 있으며, 독립적인 벡터 인덱스보다 여러 가지 장점을 제공합니다:

  1. 데이터 관리: 벡터 데이터베이스는 데이터 저장을 위한 잘 알려진 기능들인 데이터 삽입, 삭제, 갱신 등을 쉽게 사용할 수 있습니다. 이로 인해 별도의 저장소 솔루션과 통합하기 위한 추가 작업이 필요한 FAISS와 같은 독립적인 벡터 인덱스를 사용하는 것보다 벡터 데이터 관리가 더욱 쉽고 용이합니다.
  2. 메타데이터 저장과 필터링: 벡터 데이터베이스는 각 벡터 항목과 연결된 메타데이터를 저장할 수 있습니다. 이를 통해 사용자는 더 세분화된 쿼리를 위해 추가 메타데이터 필터를 사용하여 데이터베이스를 질의할 수 있습니다.
  3. 확장성: 벡터 데이터베이스는 데이터 양과 사용자 요구사항이 증가함에 따라 확장 가능하도록 설계되어 있으며, 분산 및 병렬 처리를 지원합니다. 반면에 독립적인 벡터 인덱스는 유사한 수준의 확장성을 달성하기 위해 사용자 정의 솔루션(예: Kubernetes 클러스터 또는 유사한 시스템에서의 배포 및 관리)이 필요할 수 있습니다.
  4. 실시간 업데이트: 벡터 데이터베이스는 종종 실시간 데이터 업데이트를 지원하여 데이터에 동적인 변경을 가능케 합니다. 반면에 독립적인 벡터 인덱스는 새로운 데이터를 통합하기 위해 전체 재인덱싱 프로세스를 필요로 하기 때문에 시간과 계산 리소스를 소비할 수 있습니다.
  5. 백업과 컬렉션: 벡터 데이터베이스는 데이터베이스에 저장된 모든 데이터의 일상적인 백업 작업을 처리합니다. 또한 Pinecone은 사용자가 “컬렉션” 형태로 백업할 수 있는 특정 인덱스를 선택할 수 있도록 하여 해당 인덱스의 데이터를 나중에 사용할 수 있도록 합니다.
  6. 생태계 통합: 벡터 데이터베이스는 데이터 처리 생태계의 다른 구성 요소(예: Spark와 같은 ETL 파이프라인, Tableau와 Segment와 같은 분석 도구, Grafana와 같은 시각화 플랫폼)와 더 쉽게 통합할 수 있습니다. 이는 데이터 관리 워크플로우를 간소화시킵니다. 또한 LangChain, LlamaIndex 및 ChatGPT의 플러그인과 같은 다른 AI 관련 도구들과도 쉽게 통합할 수 있습니다.
  7. 데이터 보안 및 접근 제어: 벡터 데이터베이스는 일반적으로 내장된 데이터 보안 기능과 접근 제어 메커니즘을 제공하여 중요한 정보를 보호할 수 있습니다. 이러한 기능은 독립적인 벡터 인덱스 솔루션에서 사용할 수 없을 수도 있습니다.

요약하면, 벡터 데이터베이스는 독립적인 벡터 인덱스의 한계점(예: 확장성 문제, 불편한 통합 프로세스, 실시간 업데이트 및 내장된 보안 기능의 부재)를 해결함으로써 벡터 임베딩을 처리하기 위한 우수한 솔루션을 제공합니다. 이를 통해 더욱 효과적이고 간편한 데이터 관리 경험을 얻을 수 있습니다.

How does a vector database work?

We all know how traditional databases work (more or less)—they store strings, numbers, and other types of scalar data in rows and columns. On the other hand, a vector database operates on vectors, so the way it’s optimized and queried is quite different.

In traditional databases, we are usually querying for rows in the database where the value usually exactly matches our query. In vector databases, we apply a similarity metric to find a vector that is the most similar to our query.

A vector database uses a combination of different algorithms that all participate in Approximate Nearest Neighbor (ANN) search. These algorithms optimize the search through hashing, quantization, or graph-based search.

These algorithms are assembled into a pipeline that provides fast and accurate retrieval of the neighbors of a queried vector. Since the vector database provides approximate results, the main trade-offs we consider are between accuracy and speed. The more accurate the result, the slower the query will be. However, a good system can provide ultra-fast search with near-perfect accuracy.

Here’s a common pipeline for a vector database:


우리는 모두 전통적인 데이터베이스가 어떻게 작동하는지 (대략적으로) 알고 있습니다. 전통적인 데이터베이스는 문자열, 숫자 및 기타 유형의 스칼라 데이터를 행과 열로 저장합니다. 그러나 벡터 데이터베이스는 벡터에서 작동하기 때문에 최적화 및 쿼리 방식이 상당히 다릅니다.

전통적인 데이터베이스에서는 보통 우리의 쿼리와 정확히 일치하는 데이터베이스의 행을 조회합니다. 그러나 벡터 데이터베이스에서는 유사도 지표를 적용하여 쿼리와 가장 유사한 벡터를 찾습니다.

벡터 데이터베이스는 근사적인 최근접 이웃 (Approximate Nearest Neighbor, ANN) 검색에 참여하는 다양한 알고리즘의 조합을 사용합니다. 이러한 알고리즘은 해싱, 양자화 또는 그래프 기반 검색을 통해 검색을 최적화합니다.

이러한 알고리즘들은 쿼리된 벡터의 이웃들을 빠르고 정확하게 검색하기 위해 하나의 파이프라인으로 조합됩니다. 벡터 데이터베이스는 근사적인 결과를 제공하므로 주로 정확성과 속도 사이의 균형을 고려합니다. 결과가 더 정확할수록 쿼리가 더 느려집니다. 하지만 좋은 시스템은 거의 완벽한 정확성과 초고속 검색을 제공할 수 있습니다.

다음은 벡터 데이터베이스의 일반적인 파이프라인입니다:

Vector Database
pipeline

  1. Indexing: The vector database indexes vectors using an algorithm such as PQ, LSH, or HNSW (more on these below). This step maps the vectors to a data structure that will enable faster searching.

  2. Querying: The vector database compares the indexed query vector to the indexed vectors in the dataset to find the nearest neighbors (applying a similarity metric used by that index)

  3. Post Processing: In some cases, the vector database retrieves the final nearest neighbors from the dataset and post-processes them to return the final results. This step can include re-ranking the nearest neighbors using a different similarity measure.

In the following sections, we will discuss each of these algorithms in more detail and explain how they contribute to the overall performance of a vector database.


  1. 인덱싱(Indexing): 벡터 데이터베이스는 PQ(PolyQuantization), LSH(Locality-Sensitive Hashing), HNSW(Hierarchical Navigable Small World)와 같은 알고리즘을 사용하여 벡터를 인덱싱합니다. 이 단계에서 벡터는 빠른 검색을 가능하게 하는 데이터 구조로 매핑됩니다.
  2. 쿼리(Querying): 벡터 데이터베이스는 인덱싱된 쿼리 벡터를 데이터셋에 인덱싱된 벡터와 비교하여 가장 가까운 이웃을 찾습니다. 이때 사용되는 유사도 지표는 해당 인덱스에 의해 적용됩니다.
  3. 후처리(Post Processing): 일부 경우에 벡터 데이터베이스는 데이터셋으로부터 최종 가장 가까운 이웃들을 검색하고 최종 결과를 반환하기 위해 후처리를 수행합니다. 이 단계는 다른 유사도 측정 방법을 사용하여 최종 가장 가까운 이웃들의 순위를 재조정하는 등을 포함할 수 있습니다.

다음 섹션에서는 각각의 이러한 알고리즘들을 자세히 설명하고 벡터 데이터베이스의 전체 성능에 어떻게 기여하는지 설명하겠습니다.

Algorithms

Several algorithms can facilitate the creation of a vector index. Their common goal is to enable fast querying by creating a data structure that can be traversed quickly. They will commonly transform the representation of the original vector into a compressed form to optimize the query process.

However, as a user of Pinecone, you don’t need to worry about the intricacies and selection of these various algorithms. Pinecone is designed to handle all the complexities and algorithmic decisions behind the scenes, ensuring you get the best performance and results without any hassle. By leveraging Pinecone’s expertise, you can focus on what truly matters – extracting valuable insights and delivering powerful AI solutions.

The following sections will explore several algorithms and their unique approaches to handling vector embeddings. This knowledge will empower you to make informed decisions and appreciate the seamless performance Pinecone delivers as you unlock the full potential of your application.


여러 알고리즘들이 벡터 인덱스를 생성하는 데 도움이 될 수 있습니다. 이들의 공통 목표는 빠른 쿼리를 가능하게 하기 위해 빠르게 탐색할 수 있는 데이터 구조를 생성하는 것입니다. 이들은 일반적으로 원래 벡터의 표현을 압축된 형태로 변환하여 쿼리 프로세스를 최적화합니다.

그러나 Pinecone을 사용하는 사용자는 이러한 다양한 알고리즘의 복잡성과 선택에 대해 걱정할 필요가 없습니다. Pinecone은 모든 복잡성과 알고리즘적 결정을 자동으로 처리하여 최고의 성능과 결과를 손쉽게 얻을 수 있도록 설계되었습니다. Pinecone의 전문 지식을 활용하여 가치 있는 인사이트를 추출하고 강력한 AI 솔루션을 제공하는 데 집중할 수 있습니다.

다음 섹션에서는 여러 알고리즘들과 벡터 임베딩을 처리하는 고유한 방법들을 탐구합니다. 이러한 지식을 통해 손쉬운 성능과 함께 Pinecone의 전체 잠재력을 활용할 수 있게 될 것입니다.

Random Projection

The basic idea behind random projection is to project the high-dimensional vectors to a lower-dimensional space using a random projection matrix. We create a matrix of random numbers. The size of the matrix is going to be the target low-dimension value we want. We then calculate the dot product of the input vectors and the matrix, which results in a projected matrix that has fewer dimensions than our original vectors but still preserves their similarity.


랜덤 프로젝션의 기본 아이디어는 높은 차원의 벡터들을 낮은 차원의 공간으로 랜덤 프로젝션 행렬을 사용하여 투영하는 것입니다. 랜덤한 숫자들로 이루어진 행렬을 생성합니다. 행렬의 크기는 우리가 원하는 목표 저차원 값이 됩니다. 그런 다음 입력 벡터와 행렬의 내적을 계산하면 원래 벡터보다 차원이 적은 투영된 행렬이 생성되는데, 이 투영된 행렬은 원래 벡터들의 유사성을 유지합니다.

Random
Projection

When we query, we use the same projection matrix to project the query vector onto the lower-dimensional space. Then, we compare the projected query vector to the projected vectors in the database to find the nearest neighbors. Since the dimensionality of the data is reduced, the search process is significantly faster than searching the entire high-dimensional space.

Just keep in mind that random projection is an approximate method, and the projection quality depends on the properties of the projection matrix. In general, the more random the projection matrix is, the better the quality of the projection will be. But generating a truly random projection matrix can be computationally expensive, especially for large datasets. Learn more about random projection.


쿼리할 때는 동일한 프로젝션 행렬을 사용하여 쿼리 벡터를 낮은 차원 공간에 투영합니다. 그런 다음, 투영된 쿼리 벡터를 데이터베이스의 투영된 벡터들과 비교하여 가장 가까운 이웃을 찾습니다. 데이터의 차원이 감소되므로 검색 과정이 전체 높은 차원 공간을 검색하는 것보다 훨씬 빠릅니다.

다만, 랜덤 프로젝션은 근사적인 방법이며, 프로젝션의 품질은 프로젝션 행렬의 특성에 따라 달라집니다. 일반적으로 프로젝션 행렬이 더 무작위적일수록 프로젝션의 품질이 좋아집니다. 하지만 정말로 완전히 무작위한 프로젝션 행렬을 생성하는 것은 특히 대규모 데이터셋의 경우 계산 비용이 매우 높을 수 있습니다. 랜덤 프로젝션에 대해 더 자세히 알아보세요.

Product Quantization

Another way to build an index is product quantization (PQ), which is a lossy compression technique for high-dimensional vectors (like vector embeddings). It takes the original vector, breaks it up into smaller chunks, simplifies the representation of each chunk by creating a representative “code” for each chunk, and then puts all the chunks back together - without losing information that is vital for similarity operations. The process of PQ can be broken down into four steps: splitting, training, encoding, and querying.


다른 인덱스를 구축하는 방법으로는 product quantization (PQ)이 있습니다. PQ는 고차원 벡터(예: 벡터 임베딩)에 대한 손실 압축 기술로서, 원래의 벡터를 더 작은 청크로 나눈 다음, 각 청크의 표현을 단순화하여 각 청크에 대한 대표적인 “코드”를 생성한 후, 모든 청크를 다시 결합하는 방식으로 동작합니다. 이 과정에서 유사도 연산에 필요한 정보를 잃지 않고 데이터를 압축합니다. PQ의 과정은 다음 네 단계로 나눌 수 있습니다: 분할(splitting), 학습(training), 인코딩(encoding) 및 쿼리(querying).

Product
Quantization

  1. Splitting -The vectors are broken into segments.

  2. Training - we build a “codebook” for each segment. Simply put - the algorithm generates a pool of potential “codes” that could be assigned to a vector. In practice - this “codebook” is made up of the center points of clusters created by performing k-means clustering on each of the vector’s segments. We would have the same number of values in the segment codebook as the value we use for the k-means clustering.

  3. Encoding - The algorithm assigns a specific code to each segment. In practice, we find the nearest value in the codebook to each vector segment after the training is complete. Our PQ code for the segment will be the identifier for the corresponding value in the codebook. We could use as many PQ codes as we’d like, meaning we can pick multiple values from the codebook to represent each segment.

  4. Querying - When we query, the algorithm breaks down the vectors into sub-vectors and quantizes them using the same codebook. Then, it uses the indexed codes to find the nearest vectors to the query vector.

The number of representative vectors in the codebook is a trade-off between the accuracy of the representation and the computational cost of searching the codebook. The more representative vectors in the codebook, the more accurate the representation of the vectors in the subspace, but the higher the computational cost to search the codebook. By contrast, the fewer representative vectors in the codebook, the less accurate the representation, but the lower the computational cost. Learn more about PQ.


PQ(Product Quantization)는 다음과 같은 과정으로 동작합니다:

  1. 분할(Splitting): 벡터들을 세그먼트(segment)로 분할합니다.
  2. 학습(Training): 각 세그먼트에 대해 “코드북”을 구축합니다. 간단히 말해, 이 알고리즘은 각 벡터의 세그먼트에 대해 k-means 클러스터링을 수행하여 생성된 클러스터의 중심점으로 구성된 잠재적인 “코드” 풀을 생성합니다. 실제로는 k-means 클러스터링에 사용되는 값과 동일한 수의 값이 세그먼트 코드북에 포함됩니다.
  3. 인코딩(Encoding): 알고리즘이 각 세그먼트에 특정 코드를 할당합니다. 실제로는 학습이 완료된 후 각 벡터 세그먼트에서 코드북의 가장 가까운 값과 대응하는 PQ 코드를 찾습니다. 우리는 필요에 따라 여러 개의 PQ 코드를 사용할 수 있으며, 이는 각 세그먼트를 표현하는 데에 코드북에서 여러 값을 선택할 수 있음을 의미합니다.
  4. 쿼리(Querying): 쿼리 시, 알고리즘은 벡터들을 서브-벡터로 분해하고 동일한 코드북을 사용하여 양자화(quantization)합니다. 그런 다음 인덱스된 코드를 사용하여 쿼리 벡터와 가장 가까운 벡터를 찾습니다.

코드북에 포함된 대표적인 벡터의 수는 표현의 정확성과 코드북을 탐색하는 계산 비용 사이의 균형을 유지하는데 필요한 것입니다. 코드북에 대표적인 벡터가 많을수록 부분 공간의 벡터 표현이 더 정확해지지만 코드북을 탐색하는 계산 비용이 높아집니다. 반대로 코드북에 대표적인 벡터가 적을수록 표현의 정확성이 낮아지지만 계산 비용이 낮아집니다. PQ에 대해 더 알아보기.

Locality-sensitive hashing

Locality-Sensitive Hashing (LSH) is a technique for indexing in the context of an approximate nearest-neighbor search. It is optimized for speed while still delivering an approximate, non-exhaustive result. LSH maps similar vectors into “buckets” using a set of hashing functions, as seen below:


Locality-Sensitive Hashing (LSH)는 근사적인 최근접 이웃 검색(approximate nearest-neighbor search)과 관련하여 인덱싱을 위한 기술입니다. 속도를 최적화한 동시에 근사적이고 전체적이지 않은 결과를 제공합니다. LSH는 유사한 벡터들을 일련의 해싱 함수를 사용하여 “버킷”으로 매핑합니다. 아래 그림에서 확인할 수 있습니다:

Locality-sensitive
hashing

To find the nearest neighbors for a given query vector, we use the same hashing functions used to “bucket” similar vectors into hash tables. The query vector is hashed to a particular table and then compared with the other vectors in that same table to find the closest matches. This method is much faster than searching through the entire dataset because there are far fewer vectors in each hash table than in the whole space.

It’s important to remember that LSH is an approximate method, and the quality of the approximation depends on the properties of the hash functions. In general, the more hash functions used, the better the approximation quality will be. However, using a large number of hash functions can be computationally expensive and may not be feasible for large datasets. Learn more about LSH.


특정 쿼리 벡터에 대해 가장 가까운 이웃들을 찾기 위해서는, 유사한 벡터들을 “버킷”으로 나누는 데 사용된 같은 해싱 함수를 사용합니다. 쿼리 벡터는 특정 테이블로 해싱되고, 그 다음 해당 테이블 내의 다른 벡터들과 비교하여 가장 가까운 일치를 찾습니다. 이 방법은 전체 데이터셋을 검색하는 것보다 훨씬 빠릅니다. 왜냐하면 각 해시 테이블에는 전체 공간보다 훨씬 적은 수의 벡터가 포함되기 때문입니다.

LSH는 근사적인 방법이므로 근사화 품질은 해싱 함수의 특성에 따라 달라집니다. 일반적으로 더 많은 해싱 함수를 사용할수록 근사화 품질이 향상됩니다. 그러나 많은 수의 해싱 함수를 사용하는 것은 계산적으로 비용이 많이 들며 대규모 데이터셋에는 적용하기 어려울 수 있습니다. LSH에 대해 더 알아보기.

Hierarchical Navigable Small World (HNSW)

HNSW creates a hierarchical, tree-like structure where each node of the tree represents a set of vectors. The edges between the nodes represent the similarity between the vectors. The algorithm starts by creating a set of nodes, each with a small number of vectors. This could be done randomly or by clustering the vectors with algorithms like k-means, where each cluster becomes a node.


HNSW(Hierarchical Navigable Small World)는 각 트리 노드가 벡터들의 집합을 나타내는 계층적인 트리 구조를 생성합니다. 노드 간의 엣지는 벡터들 간의 유사성을 나타냅니다. 이 알고리즘은 작은 수의 벡터들을 가진 노드 세트를 생성하는 것으로 시작합니다. 이는 무작위로 수행되거나 k-means와 같은 알고리즘을 사용하여 벡터들을 클러스터링하여 각 클러스터가 하나의 노드가 될 수 있습니다.

Hierarchical Navigable Small World
(HNSW)

The algorithm then examines the vectors of each node and draws an edge between that node and the nodes that have the most similar vectors to the one it has.


그 다음 알고리즘은 각 노드의 벡터들을 검사하고 해당 노드와 가장 유사한 벡터를 가진 노드들 사이에 엣지를 생성합니다. 이렇게 함으로써 트리 구조가 형성되고, 벡터들 간의 유사성에 기반하여 노드들이 서로 연결됩니다. 이렇게 생성된 트리 구조는 벡터들의 상대적 유사성을 반영하여 계층적으로 구성되므로, 유사한 벡터들을 빠르게 탐색할 수 있게 됩니다. HNSW는 효율적인 근사 알고리즘을 사용하여 벡터들 사이의 유사성을 보다 빠르고 효과적으로 파악할 수 있도록 합니다.

Hierarchical Navigable Small World
(HNSW)

When we query an HNSW index, it uses this graph to navigate through the tree, visiting the nodes that are most likely to contain the closest vectors to the query vector. Learn more about HNSW.


HNSW 인덱스를 쿼리할 때, 이 그래프를 사용하여 트리를 탐색합니다. 이 때, 쿼리 벡터에 가장 가까운 벡터들이 있을 가능성이 높은 노드들을 방문하게 됩니다. 이러한 방식으로 HNSW 인덱스는 빠르고 효과적으로 쿼리 벡터에 대한 가장 근접한 이웃 벡터들을 찾아낼 수 있습니다. HNSW에 대해 더 자세히 알고 싶다면 더 알아보시기 바랍니다.

Similarity Measures

Building on the previously discussed algorithms, we need to understand the role of similarity measures in vector databases. These measures are the foundation of how a vector database compares and identifies the most relevant results for a given query.

Similarity measures are mathematical methods for determining how similar two vectors are in a vector space. Similarity measures are used in vector databases to compare the vectors stored in the database and find the ones that are most similar to a given query vector.

Several similarity measures can be used, including:

  • Cosine similarity: measures the cosine of the angle between two vectors in a vector space. It ranges from -1 to 1, where 1 represents identical vectors, 0 represents orthogonal vectors, and -1 represents vectors that are diametrically opposed.

  • Euclidean distance: measures the straight-line distance between two vectors in a vector space. It ranges from 0 to infinity, where 0 represents identical vectors, and larger values represent increasingly dissimilar vectors.

  • Dot product: measures the product of the magnitudes of two vectors and the cosine of the angle between them. It ranges from -∞ to ∞, where a positive value represents vectors that point in the same direction, 0 represents orthogonal vectors, and a negative value represents vectors that point in opposite directions.

The choice of similarity measure will have an effect on the results obtained from a vector database. It is also important to note that each similarity measure has its own advantages and disadvantages, and it is important to choose the right one depending on the use case and requirements. Learn more about similarity measures.


이전에 논의한 알고리즘을 기반으로 하면, 벡터 데이터베이스에서 유사도 측정 방법의 역할을 이해해야 합니다. 이러한 측정 방법은 주어진 쿼리에 대해 가장 관련성이 높은 결과를 어떻게 비교하고 식별하는지의 기반이 됩니다.

유사도 측정 방법은 벡터 공간에서 두 벡터가 얼마나 유사한지를 결정하는 수학적 방법입니다. 벡터 데이터베이스에서는 유사도 측정 방법을 사용하여 데이터베이스에 저장된 벡터들을 비교하고 주어진 쿼리 벡터와 가장 유사한 벡터들을 찾습니다.

다양한 유사도 측정 방법이 있으며, 그 중 몇 가지는 다음과 같습니다:

  • 코사인 유사도: 벡터 공간에서 두 벡터 사이의 각도의 코사인 값을 측정합니다. 이 값은 -1에서 1까지 범위를 가지며, 1은 동일한 벡터를 나타내며, 0은 직교하는 벡터를 나타내고, -1은 정반대 방향의 벡터를 나타냅니다.
  • 유클리드 거리: 벡터 공간에서 두 벡터 사이의 직선 거리를 측정합니다. 이 값은 0에서 무한대까지 범위를 가지며, 0은 동일한 벡터를 나타내고, 더 큰 값은 점점 더 다른 벡터를 나타냅니다.
  • 내적: 두 벡터의 크기와 두 벡터 사이의 각도의 코사인의 곱을 측정합니다. 이 값은 -∞에서 ∞까지 범위를 가지며, 양수 값은 같은 방향을 가리키는 벡터를 나타내고, 0은 직교하는 벡터를 나타내며, 음수 값은 반대 방향을 가리키는 벡터를 나타냅니다.

유사도 측정 방법의 선택은 벡터 데이터베이스에서 얻는 결과에 영향을 미칩니다. 또한 각 유사도 측정 방법마다 장단점이 있으며, 사용 사례와 요구 사항에 따라 적절한 방법을 선택하는 것이 중요합니다. 유사도 측정 방법에 대해 더 알아보시기 바랍니다.

Filtering

Every vector stored in the database also includes metadata. In addition to the ability to query for similar vectors, vector databases can also filter the results based on a metadata query. To do this, the vector database usually maintains two indexes: a vector index and a metadata index. It then performs the metadata filtering either before or after the vector search itself, but in either case, there are difficulties that cause the query process to slow down.


데이터베이스에 저장된 모든 벡터는 메타데이터를 포함합니다. 벡터 데이터베이스는 유사한 벡터를 쿼리하는 능력뿐만 아니라 메타데이터 쿼리에 따라 결과를 필터링할 수도 있습니다. 이를 위해, 벡터 데이터베이스는 일반적으로 두 가지 인덱스를 유지합니다: 벡터 인덱스와 메타데이터 인덱스. 그런 다음, 메타데이터 필터링은 벡터 검색 자체 전후에 수행되지만, 어느 경우에도 쿼리 프로세스를 느리게 하는 어려움이 있습니다.

메타데이터 필터링은 특정 메타데이터 속성에 따라 벡터를 검색하여 원하는 결과를 얻기 위해 사용됩니다. 예를 들어, 사용자가 특정 벡터 속성 (예: 시간, 위치 등)에 따라 결과를 필터링하고 싶을 수 있습니다. 하지만 메타데이터 필터링은 두 가지 주요 문제를 안겨줍니다:

  1. 데이터 분리: 벡터 인덱스와 메타데이터 인덱스는 서로 다른 구조를 가집니다. 이는 데이터베이스가 두 인덱스를 효율적으로 유지하고 동기화하는 데 어려움을 줄 수 있습니다.
  2. 복잡성과 성능 문제: 메타데이터 쿼리에 따른 결과를 필터링하려면 두 인덱스를 함께 사용해야 합니다. 이로 인해 쿼리 프로세스가 복잡해지고 성능이 저하될 수 있습니다.

이러한 어려움에도 불구하고, 벡터 데이터베이스는 쿼리 성능을 최적화하고 결과를 신속하게 반환할 수 있도록 지속적으로 개선되고 있습니다. 메타데이터 필터링에 대한 최적화 기술과 효율적인 인덱싱 방법을 적용하여 더 나은 사용자 경험을 제공하는 것이 목표입니다.

Post-filtering and
Pre-filtering

The filtering process can be performed either before or after the vector search itself, but each approach has its own challenges that may impact the query performance:

  • Pre-filtering: In this approach, metadata filtering is done before the vector search. While this can help reduce the search space, it may also cause the system to overlook relevant results that don’t match the metadata filter criteria. Additionally, extensive metadata filtering may slow down the query process due to the added computational overhead.

  • Post-filtering: In this approach, the metadata filtering is done after the vector search. This can help ensure that all relevant results are considered, but it may also introduce additional overhead and slow down the query process as irrelevant results need to be filtered out after the search is complete.

To optimize the filtering process, vector databases use various techniques, such as leveraging advanced indexing methods for metadata or using parallel processing to speed up the filtering tasks. Balancing the trade-offs between search performance and filtering accuracy is essential for providing efficient and relevant query results in vector databases. Learn more about vector search filtering.


메타데이터 필터링은 벡터 검색 전후 어느 쪽에서든 수행될 수 있으며, 각 접근 방법에는 쿼리 성능에 영향을 미칠 수 있는 고유한 어려움이 있습니다:

  1. 선 필터링 (Pre-filtering): 이 접근 방법에서는 벡터 검색 이전에 메타데이터 필터링이 수행됩니다. 이렇게 하면 검색 공간을 줄일 수 있지만, 메타데이터 필터 기준과 일치하지 않는 관련 결과를 시스템이 놓칠 수 있습니다. 또한, 메타데이터 필터링이 과도하게 진행되면 추가적인 계산 오버헤드로 인해 쿼리 프로세스가 느려질 수 있습니다.
  2. 후 필터링 (Post-filtering): 이 접근 방법에서는 메타데이터 필터링이 벡터 검색 후에 수행됩니다. 이렇게 하면 모든 관련 결과가 고려되도록 도와줄 수 있지만, 검색이 완료된 후 관련 없는 결과를 필터링해야 하므로 추가적인 부담이 발생하여 쿼리 프로세스가 느려질 수 있습니다.

필터링 프로세스를 최적화하기 위해 벡터 데이터베이스는 메타데이터에 대한 고급 인덱싱 방법을 활용하거나 병렬 처리를 사용하여 필터링 작업을 가속화하는 등의 다양한 기술을 사용합니다. 검색 성능과 필터링 정확도 간의 균형을 맞추는 것은 벡터 데이터베이스에서 효율적이고 관련성 있는 쿼리 결과를 제공하는 데 중요합니다. 벡터 검색 필터링에 대해 더 자세히 알아보세요.

Database Operations

Unlike vector indexes, vector databases are equipped with a set of capabilities that makes them better qualified to be used in high scale production settings. Let’s take a look at an overall overview of the components that are involved in operating the database.


벡터 인덱스와 달리, 벡터 데이터베이스는 고규모 프로덕션 환경에서 사용하기에 더 적합하도록 여러 기능을 갖추고 있습니다. 데이터베이스 운영에 관여하는 구성 요소에 대해 전반적인 개요를 살펴보겠습니다.

Database
Operations

Performance and Fault tolerance

Performance and fault tolerance are tightly related. The more data we have, the more nodes that are required - and the bigger chance for errors and failures. As is the case with other types of databases, we want to ensure that queries are executed as quickly as possible even if some of the underlying nodes fail. This could be due to hardware failures, network failures, or other types of technical bugs. This kind of failure could result in downtime or even incorrect query results.

To ensure both high performance and fault tolerance, vector databases use sharding and replication apply the following:

  1. Sharding - partitioning the data across multiple nodes. There are different methods for partitioning the data - for example, it can be partitioned by the similarity of different clusters of data so that similar vectors are stored in the same partition. When a query is made, it is sent to all the shards and the results are retrieved and combined. This is called the “scatter-gather” pattern.

  2. Replication - creating multiple copies of the data across different nodes. This ensures that even if a particular node fails, other nodes will be able to replace it. There are two main consistency models: eventual consistency and strong consistency. Eventual consistency allows for temporary inconsistencies between different copies of the data which will improve availability and reduce latency but may result in conflicts and even data loss. On the other hand, strong consistency requires that all copies of the data are updated before a write operation is considered complete. This approach provides stronger consistency but may result in higher latency.


성능과 내결함성은 밀접한 관련이 있습니다. 데이터 양이 증가하면 더 많은 노드가 필요하며, 오류와 장애가 발생할 가능성도 커집니다. 다른 유형의 데이터베이스와 마찬가지로 쿼리가 가능한 빠른 시간 내에 실행되도록 보장하고, 백엔드 노드의 일부가 실패한 경우에도 문제없이 처리될 수 있도록 하기 위해 벡터 데이터베이스는 샤딩(sharding)과 복제(replication)를 적용합니다.

  1. 샤딩: 데이터를 여러 노드에 분할하는 것을 샤딩이라고 합니다. 데이터를 어떻게 분할할지에는 다양한 방법이 있으며, 예를 들어 유사한 벡터를 동일한 파티션에 저장하도록 데이터를 분할할 수 있습니다. 쿼리가 실행되면 모든 샤드로 보내지며, 결과는 검색하여 합칩니다. 이를 “scatter-gather” 패턴이라고 합니다.
  2. 복제: 데이터를 여러 노드에 복제하여 특정 노드에 장애가 발생한 경우 다른 노드에서 대체할 수 있도록 합니다. 이때 주요 일관성 모델로는 이벤트 기반 일관성(eventual consistency)과 강한 일관성(strong consistency) 두 가지가 있습니다. 이벤트 기반 일관성은 일시적인 데이터 불일치를 허용하며 가용성을 높이고 지연 시간을 줄일 수 있지만, 충돌과 데이터 손실이 발생할 수 있습니다. 강한 일관성은 쓰기 작업이 완료되기 전에 모든 데이터 복사본이 업데이트되어야 합니다. 이 접근 방식은 더 강력한 일관성을 제공하지만 지연 시간이 높아질 수 있습니다.

Monitoring

To effectively manage and maintain a vector database, we need a robust monitoring system that tracks the important aspects of the database’s performance, health, and overall status. Monitoring is critical for detecting potential problems, optimizing performance, and ensuring smooth production operations. Some aspects of monitoring a vector database include the following:


벡터 데이터베이스를 효율적으로 관리하고 유지하기 위해 강력한 모니터링 시스템이 필요합니다. 데이터베이스의 성능, 상태, 건강 상태를 추적하는 모니터링은 잠재적인 문제를 감지하고 성능 최적화를 위한 조치를 취하는 데 필수적입니다. 리소스 사용, 쿼리 성능, 시스템 건강 상태 등의 측면을 모니터링합니다.

  1. Resource usage - monitoring resource usage, such as CPU, memory, disk space, and network activity, enables the identification of potential issues or resource constraints that could affect the performance of the database.

  2. Query performance - query latency, throughput, and error rates may indicate potential systemic issues that need to be addressed.

  3. System health - overall system health monitoring includes the status of individual nodes, the replication process, and other critical components.


벡터 데이터베이스를 모니터링하는 데에는 다음과 같은 몇 가지 측면이 포함됩니다:

  1. 자원 사용량 모니터링: CPU, 메모리, 디스크 공간, 네트워크 활동과 같은 자원 사용량을 모니터링하여 잠재적인 문제나 자원 제한 사항을 식별하는 데 도움이 됩니다. 데이터베이스의 성능에 영향을 미칠 수 있는 자원 제약 사항을 파악할 수 있습니다.
  2. 쿼리 성능 모니터링: 쿼리 지연 시간, 처리량, 오류율 등은 잠재적인 시스템적 문제를 나타낼 수 있습니다. 쿼리 성능 모니터링을 통해 시스템의 성능 향상을 위한 개선 사항을 확인할 수 있습니다.
  3. 시스템 상태 모니터링: 개별 노드의 상태, 복제 프로세스 및 기타 중요한 구성 요소의 전반적인 시스템 상태 모니터링을 포함합니다. 시스템의 전반적인 건강 상태를 모니터링하여 잠재적인 문제를 조기에 감지하고 대응할 수 있습니다.

Access-control

Access control is the process of managing and regulating user access to data and resources. It is a vital component of data security, ensuring that only authorized users have the ability to view, modify, or interact with sensitive data stored within the vector database.


접근 제어는 사용자가 데이터와 리소스에 접근하는 것을 관리하고 규제하는 과정입니다. 데이터 보안의 중요한 구성 요소로서, 인가된 사용자만이 벡터 데이터베이스에 저장된 민감한 정보를 볼 수 있고, 수정하거나 상호 작용할 수 있도록 보장합니다. 데이터 보호, 규정 준수, 감사 추적 등의 이유로 접근 제어는 중요합니다.

Access control is important for several reasons:

  1. Data protection: As AI applications often deal with sensitive and confidential information, implementing strict access control mechanisms helps safeguard data from unauthorized access and potential breaches.

  2. Compliance: Many industries, such as healthcare and finance, are subject to strict data privacy regulations. Implementing proper access control helps organizations comply with these regulations, protecting them from legal and financial repercussions.

  3. Accountability and auditing: Access control mechanisms enable organizations to maintain a record of user activities within the vector database. This information is crucial for auditing purposes, and when security breaches happen, it helps trace back any unauthorized access or modifications.

  4. Scalability and flexibility: As organizations grow and evolve, their access control needs may change. A robust access control system allows for seamless modification and expansion of user permissions, ensuring that data security remains intact throughout the organization’s growth.


접근 제어는 여러 가지 이유로 중요합니다:

  1. 데이터 보호: 인공지능 애플리케이션은 종종 민감하고 비밀스러운 정보를 다루기 때문에, 엄격한 접근 제어 메커니즘을 구현함으로써 무단 접근과 잠재적인 위반으로부터 데이터를 보호할 수 있습니다.
  2. 규정 준수: 의료 및 금융과 같은 많은 산업은 엄격한 데이터 개인 정보 보호 규정에 따라야 합니다. 적절한 접근 제어를 구현함으로써 조직은 이러한 규정을 준수하여 법적 및 재정적인 영향으로부터 보호받을 수 있습니다.
  3. 책임과 감사: 접근 제어 메커니즘을 통해 조직은 벡터 데이터베이스 내에서 사용자 활동을 기록할 수 있습니다. 이 정보는 감사 목적으로 중요하며, 보안 침해가 발생한 경우 무단 접근이나 수정을 추적하는 데 도움이 됩니다.
  4. 확장성과 유연성: 조직이 성장하고 발전함에 따라 접근 제어 요구사항이 변경될 수 있습니다. 견고한 접근 제어 시스템은 사용자 권한의 원활한 수정과 확장을 가능하게 하여 데이터 보안이 조직의 성장 과정에서 계속 유지되도록 합니다.

Backups and collections

When all else fails, vector databases offer the ability to rely on regularly created backups. These backups can be stored on external storage systems or cloud-based storage services, ensuring the safety and recoverability of the data. In case of data loss or corruption, these backups can be used to restore the database to a previous state, minimizing downtime and impact on the overall system. With Pinecone, users can choose to back up specific indexes as well and save them as “collections,” which can later be used to populate new indexes.


벡터 데이터베이스는 정기적으로 생성된 백업을 의존할 수 있습니다. 이러한 백업은 외부 저장 시스템이나 클라우드 기반 저장 서비스에 저장될 수 있으며, 데이터의 안전성과 복구 가능성을 보장합니다. 데이터 손실이나 훼손이 발생한 경우 이러한 백업을 사용하여 데이터베이스를 이전 상태로 복원할 수 있습니다. Pinecone을 사용하면 사용자는 특정 인덱스를 백업할 수 있는 “컬렉션”으로 선택하여 저장할 수 있습니다.

다른 모든 방법들이 실패했을 때에도, 벡터 데이터베이스는 정기적으로 생성된 백업에 의존할 수 있는 기능을 제공합니다. 이러한 백업은 외부 저장 시스템이나 클라우드 기반의 저장 서비스에 저장될 수 있으며, 데이터의 안전성과 복구 가능성을 보장합니다. 데이터 손실이나 손상이 발생할 경우, 이러한 백업을 사용하여 데이터베이스를 이전 상태로 복원할 수 있으며, 다운타임을 최소화하고 전체 시스템에 미치는 영향을 최소화할 수 있습니다. Pinecone을 사용하면 사용자는 특정 인덱스를 백업으로 선택하고 “컬렉션”으로 저장할 수 있으며, 이후에 새로운 인덱스를 생성하는 데 사용할 수 있습니다.

API and SDKs

This is where the rubber meets the road: Developers who interact with the database want to do so with an easy-to-use API, using a toolset that is familiar and comfortable. By providing a user-friendly interface, the vector database API layer simplifies the development of high-performance vector search applications.

In addition to the API, vector databases would often provide programming language specific SDKs that wrap the API. The SDKs make it even easier for developers to interact with the database in their applications. This allows developers to concentrate on their specific use cases, such as semantic text search, generative question-answering, hybrid search, image similarity search, or product recommendations, without having to worry about the underlying infrastructure complexities.


이것이 실질적으로 가장 중요한 부분입니다: 데이터베이스와 상호작용하는 개발자들은 친숙하고 편안한 도구로 쉽게 API를 사용하고 싶어합니다. 사용자 친화적인 인터페이스를 제공함으로써 벡터 데이터베이스 API 계층은 고성능의 벡터 검색 애플리케이션 개발을 간소화합니다.

API와 함께 벡터 데이터베이스는 종종 프로그래밍 언어별 SDK를 제공합니다. 이 SDK는 API를 더 쉽게 사용할 수 있도록 감싸는 역할을 합니다. 이를 통해 개발자들은 의미적 텍스트 검색, 생성형 질의응답, 하이브리드 검색, 이미지 유사성 검색, 제품 추천 등과 같은 특정 사용 사례에 집중할 수 있으며, 기반이 되는 인프라 복잡성에 대해 걱정하지 않아도 됩니다.

Summary

The exponential growth of vector embeddings in fields such as NLP, computer vision, and other AI applications has resulted in the emergence of vector databases as the computation engine that allows us to interact effectively with vector embeddings in our applications.

Vector databases are purpose-built databases that are specialized to tackle the problems that arise when managing vector embeddings in production scenarios. For that reason, they offer significant advantages over traditional scalar-based databases and standalone vector indexes.

In this post, we reviewed the key aspects of a vector database, including how it works, what algorithms it uses, and the additional features that make it operationally ready for production scenarios. We hope this helps you understand the inner workings of vector databases. Luckily, this isn’t something you must know to use Pinecone. Pinecone takes care of all of these considerations (and then some) and frees you to focus on the rest of your application.


벡터 임베딩의 지수적인 성장은 자연어 처리(NLP), 컴퓨터 비전 등의 분야에서 벡터 데이터베이스의 등장으로 이어지고 있습니다. 벡터 데이터베이스는 벡터 임베딩을 효과적으로 처리할 수 있도록 특화된 목적의 데이터베이스로, 실제 운영 환경에서 벡터 임베딩을 관리하는 데 필요한 문제를 해결하는 데 중요한 장점을 제공합니다. 이러한 이유로 기존의 전통적인 스칼라 기반 데이터베이스와 독립형 벡터 인덱스보다 훨씬 우수한 성능을 발휘합니다.

이 글에서는 벡터 데이터베이스의 주요 측면, 작동 방식, 사용하는 알고리즘 및 운영 환경에서 사용하기 위한 추가적인 기능 등을 검토했습니다. 이를 통해 벡터 데이터베이스의 내부 동작 방식을 이해하는 데 도움이 되기를 바랍니다. 다행히도, Pinecone을 사용하는 데에는 이러한 모든 고려 사항을 알 필요가 없습니다. Pinecone은 이러한 모든 고려 사항을 처리하고 추가적인 기능을 제공하여 사용자가 나머지 애플리케이션에 집중할 수 있도록 도와줍니다.


comments powered by Disqus