Understanding Compound Indexes
Introduction
Welcome back to Indexes and Performances! You're now on lesson three, building on the indexing fundamentals we covered previously. In the last lesson, we learned how to create indexes on individual properties like name or email. But what happens when your queries frequently filter on multiple properties together? For example, finding users in a specific city who are above a certain age, or locating orders from a particular customer within a date range.
Creating separate indexes for each property might not be enough. In this lesson, we'll explore compound indexes, also known as composite indexes, which allow Neo4j to optimize queries that filter on multiple properties simultaneously. We'll learn when they're beneficial, how to create them, and understand the important role that property order plays in their effectiveness.
Understanding Compound Indexes
A compound index is an index built on multiple properties of the same node or relationship type, rather than just one. Think of it like an organized filing system that sorts documents first by department, then by date within each department. This dual-level organization lets you quickly find specific combinations, such as all documents from the engineering department created in March.
Similarly, a compound index on (city, age) creates a structure that organizes nodes first by city, then by age within each city. This structure becomes powerful when queries need to filter on both properties because Neo4j can navigate directly to the relevant subset of data without examining nodes that don't match either criterion. The database maintains this multi-property structure automatically as data changes, keeping it synchronized with your graph.
When Compound Indexes Make Sense
Compound indexes shine in specific scenarios where your query patterns are predictable and consistent. The most obvious case is when you frequently filter on the same combination of properties together. For instance, if your application regularly searches for users by combining location and demographic filters, or finds products by category and price range, these repeated patterns make excellent candidates for compound indexes.
Another scenario involves queries where one property narrows down the dataset significantly, and a second property provides additional filtering within that subset. The compound index can efficiently handle both steps in a single lookup operation. However, compound indexes are less helpful when your queries filter on different property combinations each time, or when you often search by just one of the indexed properties in isolation.
