@@ -874,6 +874,8 @@ HnswSearchLayer(char *base, Datum q, List *ep, int ef, int lc, Relation index, F
874874for (int i = 0 ;i < unvisitedLength ;i ++ )
875875{
876876HnswElement eElement ;
877+ HnswCandidate * e ;
878+ HnswPairingHeapNode * node ;
877879float eDistance ;
878880bool alwaysAdd = wlen < ef ;
879881
@@ -883,6 +885,9 @@ HnswSearchLayer(char *base, Datum q, List *ep, int ef, int lc, Relation index, F
883885{
884886eElement = unvisited [i ].element ;
885887eDistance = GetElementDistance (base ,eElement ,q ,procinfo ,collation );
888+
889+ if (!(eDistance < f -> distance || alwaysAdd ))
890+ continue ;
886891}
887892else
888893{
@@ -893,41 +898,38 @@ HnswSearchLayer(char *base, Datum q, List *ep, int ef, int lc, Relation index, F
893898/* Avoid any allocations if not adding */
894899eElement = NULL ;
895900HnswLoadElementImpl (blkno ,offno ,& eDistance ,& q ,index ,procinfo ,collation ,inserting ,alwaysAdd ?NULL :& f -> distance ,& eElement );
896- }
897901
898- if (eDistance < f -> distance || alwaysAdd )
899- {
900- HnswCandidate * e ;
901- HnswPairingHeapNode * node ;
902+ if (eElement == NULL )
903+ continue ;
904+ }
902905
903- Assert (!eElement -> deleted );
906+ Assert (!eElement -> deleted );
904907
905- /* Make robust to issues */
906- if (eElement -> level < lc )
907- continue ;
908+ /* Make robust to issues */
909+ if (eElement -> level < lc )
910+ continue ;
908911
909- /* Create a new candidate */
910- e = palloc (sizeof (HnswCandidate ));
911- HnswPtrStore (base ,e -> element ,eElement );
912- e -> distance = eDistance ;
912+ /* Create a new candidate */
913+ e = palloc (sizeof (HnswCandidate ));
914+ HnswPtrStore (base ,e -> element ,eElement );
915+ e -> distance = eDistance ;
913916
914- node = CreatePairingHeapNode (e );
915- pairingheap_add (C ,& node -> c_node );
916- pairingheap_add (W ,& node -> w_node );
917+ node = CreatePairingHeapNode (e );
918+ pairingheap_add (C ,& node -> c_node );
919+ pairingheap_add (W ,& node -> w_node );
917920
918- /*
919- * Do not count elements being deleted towards ef when
920- *vacuuming. It would be ideal to do this for inserts as
921- * well, but this could affect insert performance.
922- */
923- if (CountElement (base ,skipElement ,eElement ))
924- {
925- wlen ++ ;
921+ /*
922+ * Do not count elements being deleted towards ef when vacuuming.
923+ * It would be ideal to do this for inserts as well, but this
924+ * could affect insert performance.
925+ */
926+ if (CountElement (base ,skipElement ,eElement ))
927+ {
928+ wlen ++ ;
926929
927- /* No need to decrement wlen */
928- if (wlen > ef )
929- pairingheap_remove_first (W );
930- }
930+ /* No need to decrement wlen */
931+ if (wlen > ef )
932+ pairingheap_remove_first (W );
931933}
932934}
933935}