Database Requirements for Artificial Intelligence Use Cases
local graph
Chapter 15 — Database Requirements for Artificial Intelligence Use Cases
Section titled “Chapter 15 — Database Requirements for Artificial Intelligence Use Cases”Database Requirements for Artificial Intelligence Use Cases
Section titled “Database Requirements for Artificial Intelligence Use Cases”AI applications, especially l arge l anguage m odels (LLMs) and g enerative AI (GenAI), are changing how we access information and interact with technology. Today, users expect systems to interpret intent, not just return rows. This shift is forcing databases to evolve beyond their traditional role. For example, even simple AI-driven capabilities such as semantic search, r etrieval- a ugmented g eneration (RAG), or natural-language question-answering require databases to handle patterns, meanings, and relationships that cannot be captured by structured columns alone.
The underlying database systems must now meet new requirements, differing from their traditional development. Many conventional database models have been effective for structured data and ensuring transaction integrity, but are not always ideal for AI workloads in real-world scenarios. These workloads frequently depend on understanding unstructured content, performing similarity search across high-dimensional vectors, and working closely with LLM-generated embeddings.
This chapter examines the main motivations behind these challenges in detail and will serve as a reference for how PostgreSQL is addressing them through its inherent extensibility. It also discusses the need for processing unstructured content (such as text and images), the mathematics behind finding semantic similarity (nearest neighbor search), and the importance of embeddings and their connection to LLMs and foundation models.
This chapter covers the following topics:
- How AI database requirements differ from traditional applications
- Working with unstructured data such as text, images, and audio
- Understanding embeddings and vector data
- Nearest neighbor search and vector similarity
- Integrating PostgreSQL with LLMs and AI services
- Managing, indexing, and scaling vector data for AI workloads
Your purchase includes a free PDF copy + code bundle
Working with natural language and unstructured data
Section titled “Working with natural language and unstructured data”One of the most significant shifts introduced by AI applications is the paramount importance of unstructured data. Unlike the neatly organized rows and columns of traditional relational databases, much of the information critical to AI (especially for LLMs and GenAI) exists in formats such as natural language text, images, audio, and video. Databases supporting AI applications must be adept at not just storing, but also efficiently processing, querying, and indexing this type of data.
When working with natural language and unstructured data, several considerations come into play, directly influencing database requirements for AI applications. Unlike conventional applications that typically operate on rigid schemas and structured data, AI applications, especially those utilizing LLMs, must grapple with the inherent variability, ambiguity, and vastness of human language and diverse media.
Data considerations for natural language
Section titled “Data considerations for natural language”As AI systems increasingly rely on natural language understanding, the characteristics of the data itself become a defining part of the data challenge. Natural language has different requirements from traditional structured records: it grows quickly, comes in many formats, carries ambiguity, and requires meaning to be extracted before it becomes useful.
Before diving into PostgreSQL’s capabilities, it is important to understand the core data considerations that help AI applications work with text and other unstructured inputs:
- Volume and v elocity: Natural language data (text, audio, and video) is often generated at a high volume and velocity, from social media feeds to customer service interactions. Databases must scale horizontally (scale out by adding nodes/servers, rather than scaling up a single server) and be able to handle high ingestion rates. PostgreSQL, with proper scaling, can handle rapid ingestion rates.
- Variety: The diversity of unstructured data types (e.g., plain text, PDFs, images with embedded text, and audio transcripts) means a single data structure is insufficient. The database needs to accommodate polymorphic data structures, which PostgreSQL can handle.
- Veracity and v alidity: Unstructured data can be noisy, inconsistent, and contain errors. The database system needs mechanisms to store and potentially clean and standardize this data for quality, often involving integration with external data cleaning tools. PostgreSQL can store and potentially preprocess this data for quality, frequently integrating with external data cleaning tools.
- Semantic m eaning: The core challenge is not just storing the data but extracting its meaning. For example, a customer review saying, This product is amazing! carries a positive sentiment that needs to be captured, not just the raw text.
These characteristics shape what AI systems need from a database. They influence how data should be stored, processed, and queried. The considerations above therefore translate into specific database requirements that support AI workloads.
How it converts to database requirements
Section titled “How it converts to database requirements”These considerations translate directly into specific database requirements that differentiate AI applications from traditional ones:
- Flexible s chema and d iverse d ata t ype s upport: Traditional relational databases excel with fixed tabular schemas. AI applications demand databases that can store and query unstructured data types natively, such as
TEXT,JSONB,BYTEA(for images/audio), and crucially,VECTORfor embeddings. This enables the seamless integration of different data formats without complex transformations. PostgreSQL supportsTEXT,JSONB, andBYTEA(for images/audio) natively, and, through its extension architecture, addsVECTORsupport via thePGVECTORextension for AI embeddings. PostgreSQL’s extensibility provides the foundation for polymorphism. - Advanced i ndexing and s earch c apabilities: Beyond simple exact-match queries, AI applications require sophisticated search functionalities. This includes the following:
- Full-text search: For keyword-based retrieval within large text documents (e.g., finding all product descriptions containing eco-friendly)
- Vector similarity search **(**n earest n eighbor s earch): Essential for finding semantically similar items based on their embedding representations (e.g., finding products similar to a user’s previous purchase, even if keywords don’t match)
- Hybrid search: Combining keyword and semantic search for more relevant results
- Full-text search: For keyword-based retrieval within large text documents (e.g., finding all product descriptions containing eco-friendly)
- Scalability for u nstructured d ata s torage and p rocessing: Storing petabytes of unstructured data, along with its processed forms (such as embeddings), requires a highly scalable storage solution. Furthermore, the database must support the distributed processing of this data for tasks such as feature extraction or re-indexing. PostgreSQL can be configured to support the distributed processing of this type of data.
- Integration with AI/ML f rameworks: The database should not be a silo. It requires efficient connectors and APIs to interact with popular AI/ML frameworks (e.g., TensorFlow and PyTorch) for model training, embedding generation, and inference deployment. This minimizes data movement and improves overall pipeline efficiency.
Before exploring these capabilities in more detail, it helps to see how these requirements appear in a real-world application. Comparing a traditional system with an AI-enabled one makes the differences clearer.
AI applications vs. Conventional applications: An e-commerce example
Section titled “AI applications vs. Conventional applications: An e-commerce example”To illustrate the difference, let’s use the e-commerce platform that we introduced in Chapter 3*,*A Sample E-Commerce Application. E-commerce systems naturally generate a mix of structured information (products and orders) and unstructured content (descriptions and images), making it an ideal example for demonstrating how AI workloads interact with a database, embedding, and vector search.
Let’s look at a conventional e-commerce application:
- Goal: Manage product catalog, process orders, and track inventory.
- Data: Primarily structured data in relational tables (e.g., a
productstable with columns such asid,label,price, andqty, and asales_transactiontable withid,customer_id, andtransaction_date). - Database i nteractions: SQL queries for **Create,****Read,****Update,**Delete (CRUD) operations.
Findallproductsunder$50is a typical query. - Database r equirements: ACID compliance, strong transactional integrity, and efficient joins.
This traditional model of e-commerce works well for operational needs, but it highlights the gap when moving toward AI-driven experiences, such as semantic search, personalized recommendations, or intent-based queries, which require understanding the meaning, context, and similarity across unstructured data. This sets the stage for why embeddings, vector search, and database extensibility become essential in modern AI-powered systems.
AI-powered e-commerce application (with LLMs/GenAI features)
Section titled “AI-powered e-commerce application (with LLMs/GenAI features)”As we extend the same e-commerce platform into an AI-driven platform, the nature of the workload changes dramatically. The system is no longer just retrieving rows or enforcing transactional integrity; it should be understanding the user intent and product meaning, comparing items, and generating content if needed. This shift introduces a richer blend of data types, new forms of computation, and deeper interactions between the application. The following points highlight how these AI capabilities change database responsibilities:
- Goal: Provide personalized recommendations, power natural language search, generate dynamic product descriptions, and analyze customer sentiment from reviews.
- Data:
- Structured: Same
productandsales_transactiondata as conventional- Unstructured: Product descriptions (long-form text), customer reviews, images of products, user search queries (natural language), and possibly audio/video of customer support interactions
- Derived **(**e mbeddings): Vector representations of product descriptions, customer reviews, and user queries
- Structured: Same
- Database i nteractions:
- Natural l anguage s earch: A user types
Showmecomfortableshoesforhiking. The database needs to understand the intent, convert it into an embedding (either via an in-database embedding function, keeping the model close to the database, or via the application layer), and find semantically similar product embeddings, not just keywords.- Recommendation e ngine:
RecommendproductssimilartowhatIjustbought. The database looks up the embedding of the purchased item and finds the nearest neighbor product embeddings. - Sentiment a nalysis: Ingests customer reviews, and the database may store sentiment scores derived from LLMs, allowing queries such as
Findallproductswithnegativesentimentreviewsaboutdurability. - Generative AI for p roduct d escriptions: The database might store templates and raw product features, which an LLM uses to generate unique, engaging descriptions.
- Recommendation e ngine:
- Natural l anguage s earch: A user types
- Database r equirements: All conventional requirements, plus flexible schema for unstructured data, robust vector indexing (e.g., HNSW and IVFFlat), efficient vector similarity search, scalability for massive data volumes, and strong integration capabilities with external AI services or in-database AI functions. (For PostgreSQL indexing fundamentals and selection guidance, see Chapter 7*,*Designing for High-Transaction Volumes and Writing Efficient Transactional Code.)
In essence, while conventional applications focus on managing and querying well-defined, atomic pieces of information, AI applications delve into the nuanced meaning, relationships, and patterns within vast and diverse datasets, demanding a database that is inherently aware of and optimized for these complex analytical and semantic tasks.
Identifying nearest neighbors in multi-dimensional search spaces
Section titled “Identifying nearest neighbors in multi-dimensional search spaces”Another cornerstone of many modern AI applications, particularly those leveraging machine learning and deep learning, is the ability to efficiently identify nearest neighbors within multi-dimensional search spaces. This concept is fundamental to tasks such as recommendation systems, anomaly detection, image recognition, and natural language processing.
At its core, a multi-dimensional search space refers to data where each item is represented not by a single value, but by a collection of values, or features, that describe it. When these features are numerical, they can be thought of as coordinates with dimensions ranging from hundreds to thousands in a high-dimensional geometric space. (See Chapter 16*,*Vectors and Indexing for AI with pgvector for a quick primer on vectors and distance metrics.) For example, an image might be represented by thousands of numerical features describing its colors, textures, and shapes. A user’s preference profile could be represented by a vector of their ratings for different movie genres.
The nearest neighbor problem then becomes: G iven a specific data point (a “query *vector”),*find the data points in the database that are most similar. Similarity in this context is typically measured by distance metrics in the multi-dimensional space, such as Euclidean distance or cosine similarity. A smaller distance or a higher cosine similarity indicates greater semantic resemblance.
Why is nearest neighbor search crucial for AI?
Section titled “Why is nearest neighbor search crucial for AI?”Modern AI systems rely not just on retrieving information, but on finding what is most similar in meaning, intent, or behavior. This requires comparing dimensional embeddings (mathematical representations of data such as text, images, and products) to determine which items are closest to one another in semantic search. Nearest neighbor search becomes an important backbone of AI-driven capabilities. The following examples illustrate how this plays out in the real world, especially within the e-commerce context:
- Recommendation s ystems: If a user likes movie A, finding similar movies (its nearest neighbors in a movie feature space) is the basis for recommending new content.
- E-commerce e xample: A customer buys a vintage leather messenger bag. The system uses nearest neighbor search on product embeddings to recommend other vintage-style accessories, leather goods, or work bags that are semantically similar, even if they don’t share exact keywords in their descriptions. In practice, recommendation systems also apply business rules such as recency and “already purchased” filters to avoid suggesting duplicates.
- Semantic s earch: Instead of keyword matching, users can search for the meaning of a query. The query is converted into an embedding, and then nearest neighbors in the embedding space represent semantically similar documents or concepts.
- E-commerce e xample: A customer searches for
durablefootwearforoutdooradventures. The database, using nearest neighbor search on shoe embeddings, can return results forhikingboots,trailrunningshoes, orwaterprooftrekkingsandals, understanding the underlying intent rather than just matching literal words.
- E-commerce e xample: A customer searches for
- Anomaly d etection: Data points that are far from their closest neighbors might be considered anomalies or outliers, useful for fraud detection or identifying system errors.
- E-commerce e xample: A customer’s purchasing pattern suddenly deviates significantly from their usual behavior (e.g., buying a large quantity of high-value electronics when they typically buy low-cost apparel). By representing purchase history as a vector, nearest neighbor search can flag this as an anomaly for potential fraud investigation.
- Clustering and c lassification: Many machine learning algorithms rely on identifying clusters of similar data points or classifying new data based on the characteristics of its nearest neighbors.
- E-commerce e xample: Grouping customer reviews into positive sentiment, negative sentiment, or feature request clusters by analyzing the similarity of their embeddings. This helps retailers quickly identify common themes and product pain points.
Database requirements for AI applications: Nearest neighbor search, embeddings, and LLM integration
Section titled “Database requirements for AI applications: Nearest neighbor search, embeddings, and LLM integration”The need for efficient semantic search in polymorphic data, handled through approximate nearest neighbor search, coupled with the critical role of embeddings and LLM integration, profoundly impacts database design and requirements.
These are the core database capabilities for vector data:
- Vector d ata t ype s upport: The database must support a vector data type (e.g.,
VECTOR, orARRAYof floats) to store the multi-dimensional representations of data points (embeddings). This is paramount for seamless integration and performance. - Specialized i ndexing for h igh d imensions: Traditional B-tree or hash indexes are ineffective in high-dimensional spaces due to the curse of dimensionality. Therefore, databases need specialized a pproximate n earest n eighbor (ANN) indexes such as the following:
- Hierarchical Navigable Small World **(**HNSW): A graph-based index that is highly efficient for high-dimensional data, offering excellent search speed and recall
- Inverted File Index (IVFFlat): Divides the data into clusters and searches only relevant clusters, reducing search space
- Specialty i ndexes **(Disk-ANN,ScaNN,**and Faiss -like): Optimized for various scenarios, including large datasets and specific performance needs
- Hierarchical Navigable Small World **(**HNSW): A graph-based index that is highly efficient for high-dimensional data, offering excellent search speed and recall
- Efficient d istance f unctions: The database must provide highly optimized implementations of common distance metrics (e.g., Euclidean distance (L2), cosine similarity, and inner product) for fast similarity calculations, crucial for nearest neighbor search and semantic understanding.
- Scalability for v ector s torage and i ndexing: Just like unstructured data, vectors (embeddings) themselves can consume significant storage, and their indexes can be large. The database needs to scale to handle terabytes/petabytes of vector data and support distributed indexing and search, while also accounting for backup and recovery time objectives (RTO s) as cluster size grows.
- Concurrent s earch and e fficient i ndex u pdates: In dynamic AI applications, new data (and thus new vectors/embeddings) is constantly being added, and existing data might be updated. The database must efficiently support concurrent nearest neighbor searches while also allowing for ongoing index updates without significant performance degradation.
Management of embeddings and integration with LLMs
Section titled “Management of embeddings and integration with LLMs”The concept of embeddings is central to modern AI as a way of storing the semantics of data and requests. Embeddings are dense vector representations of polymorphic data—whether it’s words, sentences, paragraphs, images, audio, or even entire documents—that capture their semantic meaning. In essence, they transform complex, unstructured data into a numerical format that computers can understand and process mathematically.
What are embeddings?
Section titled “What are embeddings?”Think of an embedding as a unique numerical fingerprint for a piece of information. For example, the words king and queen might have embedding vectors that are very close to each other in a multi-dimensional space, reflecting their semantic similarity. The difference between the king vector and the queen vector might even represent the gender dimension. Similarly, an embedding of an image of a cat would be numerically closer to an embedding of another cat image than it would be to an embedding of a car. Of course, embeddings are not perfect: visually similar classes can sometimes be confused, so similarity search should be validated in the context of the specific model and data set.
Embeddings are typically generated by sophisticated machine learning models, most notably LLMs or specialized embedding models (e.g., Word2Vec, BERT, OpenAI’s embeddings, etc.). These models learn to map input data into a high-dimensional vector space where semantic relationships are represented by geometric distances. PostgreSQL, with its PGVECTOR extension, allows users to use the VECTOR data type, enabling them to store high-dimensional vectors in it.
Why are embeddings and LLM integration crucial?
Section titled “Why are embeddings and LLM integration crucial?”As AI applications move from keyword matching to understanding meaning, embeddings become an important bridge between databases and LLMs. They translate raw, messy, human-generated content into structured mathematical representations that capture intent, similarity, and context, supporting richer search, smarter recommendations, and a more adaptive user experience. The following use cases highlight how this integration transforms what an AI-driven system can achieve:
- Semantic u nderstanding: Embeddings allow databases to represent the meaning of data, not just its literal form. This enables semantic search, where a query such as
Italianfoodcan retrieve results for pizza or pasta, even if the word Italian isn’t present in the description.- E-commerce e xample: An e-commerce platform uses embeddings of product descriptions. A customer searches for
cozyknitwear. The system, using embeddings, understands cozy to imply warmth and comfort, and knitwear to imply sweaters, cardigans, and scarves. It then retrieves products whose embeddings are semantically close to this concept, even if the product titles don’t explicitly containcozyorknitwear.
- E-commerce e xample: An e-commerce platform uses embeddings of product descriptions. A customer searches for
- Contextual s earch (RAG): LLMs thrive on context. By storing embeddings of documents, conversations, or knowledge bases, the database can provide the LLM with relevant, semantically similar information, improving the quality and accuracy of its responses.
- E-commerce e xample: A customer asks an LLM-powered chatbot on an e-commerce site,
What'sthereturnpolicyforelectronics?. The chatbot queries the database using an embedding of this question. The database, which stores embeddings of help articles and FAQs, retrieves the most semantically relevant documents about electronics return policies. This information is then passed to the LLM, enabling it to generate an accurate and specific answer based on the store’s actual policies.
- E-commerce e xample: A customer asks an LLM-powered chatbot on an e-commerce site,
- Personalization: User preferences, historical interactions, and demographic data can all be embedded. By finding nearest neighbor embeddings of users to products, highly personalized recommendations can be delivered.
- E-commerce e xample: A user’s browser history and past purchases are converted into a user embedding. Product descriptions are also embedded. The system then finds products whose embeddings are closest to the user’s embedding, leading to highly personalized product recommendations on the homepage or in email marketing campaigns.
- Efficiency with LLMs: Instead of sending massive raw text or image data to an LLM for every query, the database can store precomputed embeddings. This reduces the computational load on the LLM and speeds up inference.
- Foundation for GenAI: Embeddings are often the input or output of generative models, guiding the generation process to create new, semantically coherent content.
- E-commerce e xample: An LLM generates unique product descriptions based on a product’s features. These generated descriptions can then be embedded and stored in the database for semantic search, ensuring consistency and discoverability. Or, a generative model could create variations of product images, and their embeddings could be used to ensure the generated images are visually similar to existing inventory.
Additional database requirements for managing embeddings and LLM integration
Section titled “Additional database requirements for managing embeddings and LLM integration”Beyond the core vector capabilities, managing embeddings and integrating with LLMs introduces further requirements:
- Integration with e mbedding g eneration s ervices/LLMs: The database needs streamlined ways to integrate with external or internal services that generate embeddings. This might involve the following:
- In-database functions: Allowing users to call external embedding models directly from SQL
- Efficient data loading and ETL: Tools to extract raw data, send it to an embedding model, and then load the resulting vectors back into the database
- API connectivity: Robust connectors for popular LLM APIs (e.g., OpenAI, Anthropic, and Hugging Face) for tasks such as RAG, where the database retrieves relevant context (via vector search) and passes it to the LLM
- In-database functions: Allowing users to call external embedding models directly from SQL
- Hybrid s earch c apabilities: The ability to combine traditional keyword-based search with semantic vector search is vital. For example, a user might search for
reddress(keyword) but also want results that are semantically similar to a formal gown (vector search). The database should support efficient execution of such hybrid queries.- E-commerce e xample: A customer searches for
cheaprunningshoes. The system first performs a keyword search forrunningshoesand then refines the results by looking for embeddings that are semantically similar tocheap(e.g., lower-priced items in the running shoe category).
- E-commerce e xample: A customer searches for
- Transactionality and c onsistency for e mbeddings: For many AI applications, it’s crucial that embeddings are managed with the same data integrity and consistency as other data. If a document is updated, its embedding should be regenerated and updated atomically.
- Real-time u pdates for e mbeddings: In dynamic environments (e.g., live chat and real-time recommendation systems), new data arrives constantly. The database needs to support efficient real-time indexing of new embeddings and immediate availability for search.
In essence, a database for AI, especially with LLMs and GenAI, transforms from merely a data store into an intelligent information hub, capable of understanding, organizing, and retrieving information based on its meaning, all powered by the ubiquitous presence and efficient management of embeddings.
Summary
Section titled “Summary”In this chapter, we covered the following key concepts:
- Distinct d atabase r equirements for AI a pplications: Unlike conventional applications that primarily deal with structured data and transactional integrity, AI applications, especially those leveraging LLMs and GenAI, demand databases capable of handling vast amounts of unstructured and polymorphic data (text, images, and audio), performing sophisticated semantic searches, and seamlessly integrating with AI models.
- Vectors as the f oundation of GenAI and LLM-based AI a pplications: This chapter highlighted that vectors are the fundamental numerical representations that capture the semantic meaning of diverse data types. These multi-dimensional numerical arrays are crucial for tasks such as semantic search, recommendation systems, and contextual understanding in LLMs.
- Vectors as a d ata type in PostgreSQL: Critically, you learned that specialized database extensions (such as
pgvectorfor PostgreSQL) enable vectors to be treated as a native, first-class data type within a traditional relational database. This enables the efficient storage, indexing, and querying of vector embeddings alongside conventional structured data, and lets developers use familiar SQL operators, functions, and aggregates in the same queries, simplifying the architecture and leveraging PostgreSQL’s robustness.
This chapter has laid the groundwork for understanding the unique demands AI places on database systems, emphasizing the critical role of unstructured polymorphic data, nearest neighbor search, and the management of embeddings as foundational elements for building the next generation of intelligent applications. PostgreSQL, through its inherent extensibility, is exceptionally well-positioned to support these requirements.
The next chapter demonstrates how PostgreSQL’s vector extension can be leveraged to integrate with LLMs, generate embeddings from both structured and unstructured data, execute AI-based searches, and generate recommendations.