पाठ 10 / 28
HNSW Index बनाना और Plan पढ़ना
Index जोड़ें और पुष्टि करें कि planner उसे उपयोग करता है।
एक कथन, नया plan
CREATE INDEX ... USING hnsw (embedding vector_l2_ops) WITH (m = 16, ef_construction = 64) HNSW graph index बनाता है। Operator class आपके query operator से मेल खानी चाहिए: <-> के लिए vector_l2_ops, <=> के लिए vector_cosine_ops, <#> के लिए vector_ip_ops। Build parameters: m (प्रति node links: ज़्यादा का अर्थ बेहतर recall और बड़ा index) और ef_construction (बनाते समय जाँचे उम्मीदवार: ऊँचे का अर्थ बेहतर graph और धीमा build)। ANALYZE के बाद EXPLAIN Order By के साथ Index Scan using ... दिखाता है, यानी planner ANN index उपयोग करेगा। Indexes bulk loading के बाद बनाएँ (तेज़ है), build के लिए समय और memory दें (maintenance_work_mem मायने रखता है), और याद रखें कि index approximate परिणाम लौटाता है।
Index बनाना और plan जाँचना, चलाकर
मैंने यह SQL Docker container में pgvector extension संस्करण 0.8.6 के साथ PostgreSQL 16 पर चलाया। CREATE INDEX और ANALYZE के बाद वही query sequential scan और sort की जगह Index Scan using big_hnsw ... Order By (embedding <-> ...) के रूप में plan होती है।
CREATE INDEX big_hnsw ON big USING hnsw (embedding vector_l2_ops) WITH (m = 16, ef_construction = 64);
ANALYZE big;
EXPLAIN (COSTS OFF)
SELECT id FROM big ORDER BY embedding <-> (SELECT embedding FROM big WHERE id = 1) LIMIT 10;
Output:
QUERY PLAN
------------------------------------------------
Limit
InitPlan 1 (returns $0)
-> Index Scan using big_pkey on big big_1
Index Cond: (id = 1)
-> Index Scan using big_hnsw on big
Order By: (embedding <-> $0)
(6 rows)Operator class मिलाएँ
vector_cosine_ops से बना index <-> query में उपयोग नहीं होता। EXPLAIN sequential scan दिखाए तो पहले यह जाँचें।
त्वरित जाँच: कैसे पुष्टि करें कि PostgreSQL HNSW index उपयोग करता है?
- EXPLAIN उस index पर Index Scan दिखाता है
- Table छोटी हो जाती है
- Row count बदलता है
- Server restart करके
Answer
EXPLAIN उस index पर Index Scan दिखाता है — Planner क्या करता है इसका स्रोत plan है।