@@ -94,6 +94,9 @@ public void advance(byte[] target) {
9494 @ Override
9595 public Weight createWeight (IndexSearcher searcher , ScoreMode scoreMode , float boost ) throws IOException {
9696 return new ConstantScoreWeight (this , boost ) {
97+ // get cardinality is not cheap enough to do when supplying scorers, so do it once per weight
98+ final long cardinality = bitmap .getLongCardinality ();
99+
97100 @ Override
98101 public Scorer scorer (LeafReaderContext context ) throws IOException {
99102 ScorerSupplier scorerSupplier = scorerSupplier (context );
@@ -117,20 +120,23 @@ public ScorerSupplier scorerSupplier(LeafReaderContext context) throws IOExcepti
117120 }
118121
119122 return new ScorerSupplier () {
120- long cost = -1 ; // calculate lazily, and only once
123+ long cost = -1 ;
124+
125+ final DocIdSetBuilder result = new DocIdSetBuilder (reader .maxDoc (), values , field );
126+ final MergePointVisitor visitor = new MergePointVisitor (result );
121127
122128 @ Override
123129 public Scorer get (long leadCost ) throws IOException {
124- DocIdSetBuilder result = new DocIdSetBuilder (reader .maxDoc (), values , field );
125- MergePointVisitor visitor = new MergePointVisitor (result );
126130 values .intersect (visitor );
127131 return new ConstantScoreScorer (weight , score (), scoreMode , result .build ().iterator ());
128132 }
129133
130134 @ Override
131135 public long cost () {
132136 if (cost == -1 ) {
133- cost = bitmap .getLongCardinality ();
137+ // rough estimate of the cost, 20 times penalty is based on the experiment results
138+ // details in https://github.com/opensearch-project/OpenSearch/pull/16936
139+ cost = cardinality * 20 ;
134140 }
135141 return cost ;
136142 }
@@ -246,7 +252,7 @@ public Query rewrite(IndexSearcher indexSearcher) throws IOException {
246252
247253 @ Override
248254 public String toString (String field ) {
249- return "BitmapIndexQuery(field=" + field + ")" ;
255+ return "BitmapIndexQuery(field=" + this . field + ")" ;
250256 }
251257
252258 @ Override
0 commit comments