Apache Lucene open-source search software
LUCENE-10436: Deprecate DocValuesFieldExistsQuery, NormsFieldExistsQuery and KnnVectorFieldExistsQuery with FieldExistsQuery (#767)
zacharymorn91e29405d8e4
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txtindex cf5a2b8a54a..39e7ec900a7 100644--- a/lucene/CHANGES.txt+++ b/lucene/CHANGES.txt@@ -98,6 +98,9 @@ Optimizations* LUCENE-10418: More `Query#rewrite` optimizations for the non-scoring case.(Adrien Grand)+* LUCENE-10436: Deprecate DocValuesFieldExistsQuery, NormsFieldExistsQuery and KnnVectorFieldExistsQuery+ with FieldExistsQuery. (Zach Chen, Michael McCandless, Adrien Grand)+* LUCENE-10481: FacetsCollector will not request scores if it does not use them. (Mike Drob)Bug Fixesdiff --git a/lucene/core/src/java/org/apache/lucene/search/DocValuesFieldExistsQuery.java b/lucene/core/src/java/org/apache/lucene/search/DocValuesFieldExistsQuery.javaindex 9c39a33b4ff..6cbf8250d7d 100644--- a/lucene/core/src/java/org/apache/lucene/search/DocValuesFieldExistsQuery.java+++ b/lucene/core/src/java/org/apache/lucene/search/DocValuesFieldExistsQuery.java@@ -17,108 +17,21 @@package org.apache.lucene.search;import java.io.IOException;-import java.util.Objects;-import org.apache.lucene.index.DocValues;-import org.apache.lucene.index.DocValuesType;import org.apache.lucene.index.FieldInfo;-import org.apache.lucene.index.IndexOptions;-import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.LeafReader;-import org.apache.lucene.index.LeafReaderContext;-import org.apache.lucene.index.PointValues;-import org.apache.lucene.index.Terms;/*** A {@link Query} that matches documents that have a value for a given field as reported by doc* values iterators.+ *+ * @deprecated Use {@link org.apache.lucene.search.FieldExistsQuery} instead.*/-public final class DocValuesFieldExistsQuery extends Query {-- private final String field;+@Deprecated+public final class DocValuesFieldExistsQuery extends FieldExistsQuery {/** Create a query that will match documents which have a value for the given {@code field}. */public DocValuesFieldExistsQuery(String field) {- this.field = Objects.requireNonNull(field);- }-- public String getField() {- return field;- }-- @Override- public boolean equals(Object other) {- return sameClassAs(other) && field.equals(((DocValuesFieldExistsQuery) other).field);- }-- @Override- public int hashCode() {- return 31 * classHash() + field.hashCode();- }-- @Override- public String toString(String field) {- return "DocValuesFieldExistsQuery [field=" + this.field + "]";- }-- @Override- public void visit(QueryVisitor visitor) {- if (visitor.acceptField(field)) {- visitor.visitLeaf(this);- }- }-- @Override- public Query rewrite(IndexReader reader) throws IOException {- boolean allReadersRewritable = true;- for (LeafReaderContext context : reader.leaves()) {- LeafReader leaf = context.reader();- Terms terms = leaf.terms(field);- PointValues pointValues = leaf.getPointValues(field);- if ((terms == null || terms.getDocCount() != leaf.maxDoc())- && (pointValues == null || pointValues.getDocCount() != leaf.maxDoc())) {- allReadersRewritable = false;- break;- }- }- if (allReadersRewritable) {- return new MatchAllDocsQuery();- }- return super.rewrite(reader);- }-- @Override- public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) {- return new ConstantScoreWeight(this, boost) {- @Override- public Scorer scorer(LeafReaderContext context) throws IOException {- DocIdSetIterator iterator = getDocValuesDocIdSetIterator(field, context.reader());- if (iterator == null) {- return null;- }- return new ConstantScoreScorer(this, score(), scoreMode, iterator);- }-- @Override- public int count(LeafReaderContext context) throws IOException {- final LeafReader reader = context.reader();- final FieldInfo fieldInfo = reader.getFieldInfos().fieldInfo(field);- if (fieldInfo == null || fieldInfo.getDocValuesType() == DocValuesType.NONE) {- return 0; // the field doesn't index doc values- } else if (reader.hasDeletions() == false) {- if (fieldInfo.getPointDimensionCount() > 0) {- return reader.getPointValues(field).getDocCount();- } else if (fieldInfo.getIndexOptions() != IndexOptions.NONE) {- return reader.terms(field).getDocCount();- }- }- return super.count(context);- }-- @Override- public boolean isCacheable(LeafReaderContext ctx) {- return DocValues.isCacheable(ctx, field);- }- };+ super(field);}/**diff --git a/lucene/core/src/java/org/apache/lucene/search/FieldExistsQuery.java b/lucene/core/src/java/org/apache/lucene/search/FieldExistsQuery.javanew file mode 100644index 00000000000..3a225f367d0--- /dev/null+++ b/lucene/core/src/java/org/apache/lucene/search/FieldExistsQuery.java@@ -0,0 +1,228 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package org.apache.lucene.search;++import java.io.IOException;+import java.util.Objects;+import org.apache.lucene.index.DocValues;+import org.apache.lucene.index.DocValuesType;+import org.apache.lucene.index.FieldInfo;+import org.apache.lucene.index.FieldInfos;+import org.apache.lucene.index.IndexOptions;+import org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.LeafReader;+import org.apache.lucene.index.LeafReaderContext;+import org.apache.lucene.index.PointValues;+import org.apache.lucene.index.Terms;++/**+ * A {@link Query} that matches documents that contain either a {@link+ * org.apache.lucene.document.KnnVectorField}, or a field that indexes norms or doc values.+ */+public class FieldExistsQuery extends Query {+ private String field;++ /** Create a query that will match that have a value for the given {@code field}. */+ public FieldExistsQuery(String field) {+ this.field = Objects.requireNonNull(field);+ }++ public String getField() {+ return field;+ }++ @Override+ public String toString(String field) {+ return "FieldExistsQuery [field=" + this.field + "]";+ }++ @Override+ public void visit(QueryVisitor visitor) {+ if (visitor.acceptField(field)) {+ visitor.visitLeaf(this);+ }+ }++ @Override+ public boolean equals(Object other) {+ return sameClassAs(other) && field.equals(((FieldExistsQuery) other).field);+ }++ @Override+ public int hashCode() {+ final int prime = 31;+ int hash = classHash();+ hash = prime * hash + field.hashCode();+ return hash;+ }++ @Override+ public Query rewrite(IndexReader reader) throws IOException {+ boolean allReadersRewritable = true;++ for (LeafReaderContext context : reader.leaves()) {+ LeafReader leaf = context.reader();+ FieldInfos fieldInfos = leaf.getFieldInfos();+ FieldInfo fieldInfo = fieldInfos.fieldInfo(field);++ if (fieldInfo == null) {+ allReadersRewritable = false;+ break;+ }++ if (fieldInfo.hasNorms()) { // the field indexes norms+ if (reader.getDocCount(field) != reader.maxDoc()) {+ allReadersRewritable = false;+ break;+ }+ } else if (fieldInfo.getVectorDimension() != 0) { // the field indexes vectors+ if (leaf.getVectorValues(field).size() != reader.maxDoc()) {+ allReadersRewritable = false;+ break;+ }+ } else if (fieldInfo.getDocValuesType()+ != DocValuesType.NONE) { // the field indexes doc values or points++ // This optimization is possible due to LUCENE-9334 enforcing a field to always uses the+ // same data structures (all or nothing). Since there's no index statistic to detect when+ // all documents have doc values for a specific field, FieldExistsQuery can only be+ // rewritten to MatchAllDocsQuery for doc values field, when that same field also indexes+ // terms or point values which do have index statistics, and those statistics confirm that+ // all documents in this segment have values terms or point values.++ Terms terms = leaf.terms(field);+ PointValues pointValues = leaf.getPointValues(field);++ if ((terms == null || terms.getDocCount() != leaf.maxDoc())+ && (pointValues == null || pointValues.getDocCount() != leaf.maxDoc())) {+ allReadersRewritable = false;+ break;+ }+ } else {+ throw new IllegalStateException(buildErrorMsg(fieldInfo));+ }+ }+ if (allReadersRewritable) {+ return new MatchAllDocsQuery();+ }+ return super.rewrite(reader);+ }++ @Override+ public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) {+ return new ConstantScoreWeight(this, boost) {+ @Override+ public Scorer scorer(LeafReaderContext context) throws IOException {+ FieldInfos fieldInfos = context.reader().getFieldInfos();+ FieldInfo fieldInfo = fieldInfos.fieldInfo(field);+ DocIdSetIterator iterator = null;++ if (fieldInfo == null) {+ return null;+ }++ if (fieldInfo.hasNorms()) { // the field indexes norms+ iterator = context.reader().getNormValues(field);+ } else if (fieldInfo.getVectorDimension() != 0) { // the field indexes vectors+ iterator = context.reader().getVectorValues(field);+ } else if (fieldInfo.getDocValuesType()+ != DocValuesType.NONE) { // the field indexes doc values+ switch (fieldInfo.getDocValuesType()) {+ case NUMERIC:+ iterator = context.reader().getNumericDocValues(field);+ break;+ case BINARY:+ iterator = context.reader().getBinaryDocValues(field);+ break;+ case SORTED:+ iterator = context.reader().getSortedDocValues(field);+ break;+ case SORTED_NUMERIC:+ iterator = context.reader().getSortedNumericDocValues(field);+ break;+ case SORTED_SET:+ iterator = context.reader().getSortedSetDocValues(field);+ break;+ case NONE:+ default:+ throw new AssertionError();+ }+ } else {+ throw new IllegalStateException(buildErrorMsg(fieldInfo));+ }++ if (iterator == null) {+ return null;+ }+ return new ConstantScoreScorer(this, score(), scoreMode, iterator);+ }++ @Override+ public int count(LeafReaderContext context) throws IOException {+ LeafReader reader = context.reader();+ FieldInfos fieldInfos = reader.getFieldInfos();+ FieldInfo fieldInfo = fieldInfos.fieldInfo(field);++ if (fieldInfo == null) {+ return 0;+ }++ if (fieldInfo.hasNorms()) { // the field indexes norms+ // If every field has a value then we can shortcut+ if (reader.getDocCount(field) == reader.maxDoc()) {+ return reader.numDocs();+ }++ return super.count(context);+ } else if (fieldInfo.getVectorDimension() != 0) { // the field indexes vectors+ return super.count(context);+ } else if (fieldInfo.getDocValuesType()+ != DocValuesType.NONE) { // the field indexes doc values+ if (reader.hasDeletions() == false) {+ if (fieldInfo.getPointDimensionCount() > 0) {+ return reader.getPointValues(field).getDocCount();+ } else if (fieldInfo.getIndexOptions() != IndexOptions.NONE) {+ return reader.terms(field).getDocCount();+ }+ }++ return super.count(context);+ } else {+ throw new IllegalStateException(buildErrorMsg(fieldInfo));+ }+ }++ @Override+ public boolean isCacheable(LeafReaderContext context) {+ FieldInfos fieldInfos = context.reader().getFieldInfos();+ FieldInfo fieldInfo = fieldInfos.fieldInfo(field);++ if (fieldInfo != null && fieldInfo.getDocValuesType() != DocValuesType.NONE) {+ return DocValues.isCacheable(context, field);+ }++ return true;+ }+ };+ }++ private String buildErrorMsg(FieldInfo fieldInfo) {+ return "FieldExistsQuery requires that the field indexes doc values, norms or vectors, but field '"+ + fieldInfo.name+ + "' exists and indexes neither of these data structures";+ }+}diff --git a/lucene/core/src/java/org/apache/lucene/search/KnnVectorFieldExistsQuery.java b/lucene/core/src/java/org/apache/lucene/search/KnnVectorFieldExistsQuery.javaindex 50e0c9a2a2b..05afcb630b2 100644--- a/lucene/core/src/java/org/apache/lucene/search/KnnVectorFieldExistsQuery.java+++ b/lucene/core/src/java/org/apache/lucene/search/KnnVectorFieldExistsQuery.java@@ -17,65 +17,17 @@package org.apache.lucene.search;-import java.io.IOException;-import java.util.Objects;-import org.apache.lucene.index.LeafReaderContext;-/*** A {@link Query} that matches documents that contain a {@link* org.apache.lucene.document.KnnVectorField}.+ *+ * @deprecated Use {@link org.apache.lucene.search.FieldExistsQuery} instead.*/-public class KnnVectorFieldExistsQuery extends Query {-- private final String field;+@Deprecated+public class KnnVectorFieldExistsQuery extends FieldExistsQuery {/** Create a query that will match documents which have a value for the given {@code field}. */public KnnVectorFieldExistsQuery(String field) {- this.field = Objects.requireNonNull(field);- }-- public String getField() {- return field;- }-- @Override- public boolean equals(Object other) {- return sameClassAs(other) && field.equals(((KnnVectorFieldExistsQuery) other).field);- }-- @Override- public int hashCode() {- return 31 * classHash() + field.hashCode();- }-- @Override- public String toString(String field) {- return "KnnVectorFieldExistsQuery [field=" + this.field + "]";- }-- @Override- public void visit(QueryVisitor visitor) {- if (visitor.acceptField(field)) {- visitor.visitLeaf(this);- }- }-- @Override- public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) {- return new ConstantScoreWeight(this, boost) {- @Override- public Scorer scorer(LeafReaderContext context) throws IOException {- DocIdSetIterator iterator = context.reader().getVectorValues(field);- if (iterator == null) {- return null;- }- return new ConstantScoreScorer(this, score(), scoreMode, iterator);- }-- @Override- public boolean isCacheable(LeafReaderContext ctx) {- return true;- }- };+ super(field);}}diff --git a/lucene/core/src/java/org/apache/lucene/search/NormsFieldExistsQuery.java b/lucene/core/src/java/org/apache/lucene/search/NormsFieldExistsQuery.javaindex d23171caa96..df3aa607f67 100644--- a/lucene/core/src/java/org/apache/lucene/search/NormsFieldExistsQuery.java+++ b/lucene/core/src/java/org/apache/lucene/search/NormsFieldExistsQuery.java@@ -16,87 +16,19 @@*/package org.apache.lucene.search;-import java.io.IOException;-import java.util.Objects;import org.apache.lucene.document.StringField;-import org.apache.lucene.index.FieldInfo;-import org.apache.lucene.index.FieldInfos;-import org.apache.lucene.index.LeafReader;-import org.apache.lucene.index.LeafReaderContext;/*** A {@link Query} that matches documents that have a value for a given field as reported by field* norms. This will not work for fields that omit norms, e.g. {@link StringField}.+ *+ * @deprecated Use {@link org.apache.lucene.search.FieldExistsQuery} instead.*/-public final class NormsFieldExistsQuery extends Query {-- private final String field;+@Deprecated+public final class NormsFieldExistsQuery extends FieldExistsQuery {/** Create a query that will match that have a value for the given {@code field}. */public NormsFieldExistsQuery(String field) {- this.field = Objects.requireNonNull(field);- }-- public String getField() {- return field;- }-- @Override- public boolean equals(Object other) {- return sameClassAs(other) && field.equals(((NormsFieldExistsQuery) other).field);- }-- @Override- public int hashCode() {- return 31 * classHash() + field.hashCode();- }-- @Override- public String toString(String field) {- return "NormsFieldExistsQuery [field=" + this.field + "]";- }-- @Override- public void visit(QueryVisitor visitor) {- if (visitor.acceptField(field)) {- visitor.visitLeaf(this);- }- }-- @Override- public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost)- throws IOException {- return new ConstantScoreWeight(this, boost) {- @Override- public Scorer scorer(LeafReaderContext context) throws IOException {- FieldInfos fieldInfos = context.reader().getFieldInfos();- FieldInfo fieldInfo = fieldInfos.fieldInfo(field);- if (fieldInfo == null || fieldInfo.hasNorms() == false) {- return null;- }- LeafReader reader = context.reader();- DocIdSetIterator iterator = reader.getNormValues(field);- return new ConstantScoreScorer(this, score(), scoreMode, iterator);- }-- @Override- public int count(LeafReaderContext context) throws IOException {- final LeafReader reader = context.reader();- final FieldInfo fieldInfo = reader.getFieldInfos().fieldInfo(field);- if (fieldInfo == null || fieldInfo.hasNorms() == false) {- return 0;- }- // If every field has a value then we can shortcut- if (reader.getDocCount(field) == reader.maxDoc()) {- return reader.numDocs();- }- return super.count(context);- }-- @Override- public boolean isCacheable(LeafReaderContext ctx) {- return true;- }- };+ super(field);}}diff --git a/lucene/core/src/test/org/apache/lucene/search/TestDocValuesFieldExistsQuery.java b/lucene/core/src/test/org/apache/lucene/search/TestDocValuesFieldExistsQuery.javadeleted file mode 100644index 3541dc7a213..00000000000--- a/lucene/core/src/test/org/apache/lucene/search/TestDocValuesFieldExistsQuery.java+++ /dev/null@@ -1,367 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-package org.apache.lucene.search;--import java.io.IOException;-import org.apache.lucene.document.BinaryPoint;-import org.apache.lucene.document.Document;-import org.apache.lucene.document.Field.Store;-import org.apache.lucene.document.LongPoint;-import org.apache.lucene.document.NumericDocValuesField;-import org.apache.lucene.document.SortedDocValuesField;-import org.apache.lucene.document.SortedNumericDocValuesField;-import org.apache.lucene.document.StringField;-import org.apache.lucene.index.DirectoryReader;-import org.apache.lucene.index.IndexReader;-import org.apache.lucene.index.NoMergePolicy;-import org.apache.lucene.index.Term;-import org.apache.lucene.search.BooleanClause.Occur;-import org.apache.lucene.store.Directory;-import org.apache.lucene.tests.index.RandomIndexWriter;-import org.apache.lucene.tests.util.LuceneTestCase;-import org.apache.lucene.tests.util.TestUtil;-import org.apache.lucene.util.BytesRef;-import org.apache.lucene.util.IOUtils;--public class TestDocValuesFieldExistsQuery extends LuceneTestCase {-- public void testRewriteWithTermsPresent() throws IOException {- Directory dir = newDirectory();- RandomIndexWriter iw = new RandomIndexWriter(random(), dir);- final int numDocs = atLeast(100);- for (int i = 0; i < numDocs; ++i) {- Document doc = new Document();- doc.add(new StringField("f", random().nextBoolean() ? "yes" : "no", Store.NO));- iw.addDocument(doc);- }- iw.commit();- final IndexReader reader = iw.getReader();- iw.close();-- assertTrue((new DocValuesFieldExistsQuery("f")).rewrite(reader) instanceof MatchAllDocsQuery);- reader.close();- dir.close();- }-- public void testRewriteWithPointValuesPresent() throws IOException {- Directory dir = newDirectory();- RandomIndexWriter iw = new RandomIndexWriter(random(), dir);- final int numDocs = atLeast(100);- for (int i = 0; i < numDocs; ++i) {- Document doc = new Document();- doc.add(new BinaryPoint("dim", new byte[4], new byte[4]));- iw.addDocument(doc);- }- iw.commit();- final IndexReader reader = iw.getReader();- iw.close();-- assertTrue((new DocValuesFieldExistsQuery("dim")).rewrite(reader) instanceof MatchAllDocsQuery);- reader.close();- dir.close();- }-- public void testNoRewrite() throws IOException {- Directory dir = newDirectory();- RandomIndexWriter iw = new RandomIndexWriter(random(), dir);- final int numDocs = atLeast(100);- for (int i = 0; i < numDocs; ++i) {- Document doc = new Document();- doc.add(new BinaryPoint("dim", new byte[4], new byte[4]));- iw.addDocument(doc);- }- for (int i = 0; i < numDocs; ++i) {- Document doc = new Document();- doc.add(new StringField("f", random().nextBoolean() ? "yes" : "no", Store.NO));- iw.addDocument(doc);- }- iw.commit();- final IndexReader reader = iw.getReader();- iw.close();-- assertFalse(- (new DocValuesFieldExistsQuery("dim")).rewrite(reader) instanceof MatchAllDocsQuery);- assertFalse((new DocValuesFieldExistsQuery("f")).rewrite(reader) instanceof MatchAllDocsQuery);- reader.close();- dir.close();- }-- public void testNoRewriteWithDocValues() throws IOException {- Directory dir = newDirectory();- RandomIndexWriter iw = new RandomIndexWriter(random(), dir);- final int numDocs = atLeast(100);- for (int i = 0; i < numDocs; ++i) {- Document doc = new Document();- doc.add(new NumericDocValuesField("dv1", 1));- doc.add(new SortedNumericDocValuesField("dv2", 1));- doc.add(new SortedNumericDocValuesField("dv2", 2));- iw.addDocument(doc);- }- iw.commit();- final IndexReader reader = iw.getReader();- iw.close();-- assertFalse(- (new DocValuesFieldExistsQuery("dv1")).rewrite(reader) instanceof MatchAllDocsQuery);- assertFalse(- (new DocValuesFieldExistsQuery("dv2")).rewrite(reader) instanceof MatchAllDocsQuery);- assertFalse(- (new DocValuesFieldExistsQuery("dv3")).rewrite(reader) instanceof MatchAllDocsQuery);- reader.close();- dir.close();- }-- public void testRandom() throws IOException {- final int iters = atLeast(10);- for (int iter = 0; iter < iters; ++iter) {- Directory dir = newDirectory();- RandomIndexWriter iw = new RandomIndexWriter(random(), dir);- final int numDocs = atLeast(100);- for (int i = 0; i < numDocs; ++i) {- Document doc = new Document();- final boolean hasValue = random().nextBoolean();- if (hasValue) {- doc.add(new NumericDocValuesField("dv1", 1));- doc.add(new SortedNumericDocValuesField("dv2", 1));- doc.add(new SortedNumericDocValuesField("dv2", 2));- doc.add(new StringField("has_value", "yes", Store.NO));- }- doc.add(new StringField("f", random().nextBoolean() ? "yes" : "no", Store.NO));- iw.addDocument(doc);- }- if (random().nextBoolean()) {- iw.deleteDocuments(new TermQuery(new Term("f", "no")));- }- iw.commit();- final IndexReader reader = iw.getReader();- final IndexSearcher searcher = newSearcher(reader);- iw.close();-- assertSameMatches(- searcher,- new TermQuery(new Term("has_value", "yes")),- new DocValuesFieldExistsQuery("dv1"),- false);- assertSameMatches(- searcher,- new TermQuery(new Term("has_value", "yes")),- new DocValuesFieldExistsQuery("dv2"),- false);-- reader.close();- dir.close();- }- }-- public void testApproximation() throws IOException {- final int iters = atLeast(10);- for (int iter = 0; iter < iters; ++iter) {- Directory dir = newDirectory();- RandomIndexWriter iw = new RandomIndexWriter(random(), dir);- final int numDocs = atLeast(100);- for (int i = 0; i < numDocs; ++i) {- Document doc = new Document();- final boolean hasValue = random().nextBoolean();- if (hasValue) {- doc.add(new NumericDocValuesField("dv1", 1));- doc.add(new SortedNumericDocValuesField("dv2", 1));- doc.add(new SortedNumericDocValuesField("dv2", 2));- doc.add(new StringField("has_value", "yes", Store.NO));- }- doc.add(new StringField("f", random().nextBoolean() ? "yes" : "no", Store.NO));- iw.addDocument(doc);- }- if (random().nextBoolean()) {- iw.deleteDocuments(new TermQuery(new Term("f", "no")));- }- iw.commit();- final IndexReader reader = iw.getReader();- final IndexSearcher searcher = newSearcher(reader);- iw.close();-- BooleanQuery.Builder ref = new BooleanQuery.Builder();- ref.add(new TermQuery(new Term("f", "yes")), Occur.MUST);- ref.add(new TermQuery(new Term("has_value", "yes")), Occur.FILTER);-- BooleanQuery.Builder bq1 = new BooleanQuery.Builder();- bq1.add(new TermQuery(new Term("f", "yes")), Occur.MUST);- bq1.add(new DocValuesFieldExistsQuery("dv1"), Occur.FILTER);- assertSameMatches(searcher, ref.build(), bq1.build(), true);-- BooleanQuery.Builder bq2 = new BooleanQuery.Builder();- bq2.add(new TermQuery(new Term("f", "yes")), Occur.MUST);- bq2.add(new DocValuesFieldExistsQuery("dv2"), Occur.FILTER);- assertSameMatches(searcher, ref.build(), bq2.build(), true);-- reader.close();- dir.close();- }- }-- public void testScore() throws IOException {- final int iters = atLeast(10);- for (int iter = 0; iter < iters; ++iter) {- Directory dir = newDirectory();- RandomIndexWriter iw = new RandomIndexWriter(random(), dir);- final int numDocs = atLeast(100);- for (int i = 0; i < numDocs; ++i) {- Document doc = new Document();- final boolean hasValue = random().nextBoolean();- if (hasValue) {- doc.add(new NumericDocValuesField("dv1", 1));- doc.add(new SortedNumericDocValuesField("dv2", 1));- doc.add(new SortedNumericDocValuesField("dv2", 2));- doc.add(new StringField("has_value", "yes", Store.NO));- }- doc.add(new StringField("f", random().nextBoolean() ? "yes" : "no", Store.NO));- iw.addDocument(doc);- }- if (random().nextBoolean()) {- iw.deleteDocuments(new TermQuery(new Term("f", "no")));- }- iw.commit();- final IndexReader reader = iw.getReader();- final IndexSearcher searcher = newSearcher(reader);- iw.close();-- final float boost = random().nextFloat() * 10;- final Query ref =- new BoostQuery(- new ConstantScoreQuery(new TermQuery(new Term("has_value", "yes"))), boost);-- final Query q1 = new BoostQuery(new DocValuesFieldExistsQuery("dv1"), boost);- assertSameMatches(searcher, ref, q1, true);-- final Query q2 = new BoostQuery(new DocValuesFieldExistsQuery("dv2"), boost);- assertSameMatches(searcher, ref, q2, true);-- reader.close();- dir.close();- }- }-- public void testMissingField() throws IOException {- Directory dir = newDirectory();- RandomIndexWriter iw = new RandomIndexWriter(random(), dir);- iw.addDocument(new Document());- iw.commit();- final IndexReader reader = iw.getReader();- final IndexSearcher searcher = newSearcher(reader);- iw.close();- assertEquals(0, searcher.count(new DocValuesFieldExistsQuery("f")));- reader.close();- dir.close();- }-- public void testAllDocsHaveField() throws IOException {- Directory dir = newDirectory();- RandomIndexWriter iw = new RandomIndexWriter(random(), dir);- Document doc = new Document();- doc.add(new NumericDocValuesField("f", 1));- iw.addDocument(doc);- iw.commit();- final IndexReader reader = iw.getReader();- final IndexSearcher searcher = newSearcher(reader);- iw.close();- assertEquals(1, searcher.count(new DocValuesFieldExistsQuery("f")));- reader.close();- dir.close();- }-- public void testFieldExistsButNoDocsHaveField() throws IOException {- Directory dir = newDirectory();- RandomIndexWriter iw = new RandomIndexWriter(random(), dir);- // 1st segment has the field, but 2nd one does not- Document doc = new Document();- doc.add(new NumericDocValuesField("f", 1));- iw.addDocument(doc);- iw.commit();- iw.addDocument(new Document());- iw.commit();- final IndexReader reader = iw.getReader();- final IndexSearcher searcher = newSearcher(reader);- iw.close();- assertEquals(1, searcher.count(new DocValuesFieldExistsQuery("f")));- reader.close();- dir.close();- }-- public void testQueryMatchesCount() throws IOException {- Directory dir = newDirectory();- RandomIndexWriter w = new RandomIndexWriter(random(), dir);-- int randomNumDocs = TestUtil.nextInt(random(), 11, 100);- int numMatchingDocs = 0;-- for (int i = 0; i < randomNumDocs; i++) {- Document doc = new Document();- // We select most documents randomly but keep two documents:- // * #0 ensures we will delete at least one document (with long between 0 and 9)- // * #10 ensures we will keep at least one document (with long greater than 9)- if (i == 0 || i == 10 || random().nextBoolean()) {- doc.add(new LongPoint("long", i));- doc.add(new NumericDocValuesField("long", i));- doc.add(new StringField("string", "value", Store.NO));- doc.add(new SortedDocValuesField("string", new BytesRef("value")));- numMatchingDocs++;- }- w.addDocument(doc);- }- w.forceMerge(1);-- DirectoryReader reader = w.getReader();- final IndexSearcher searcher = new IndexSearcher(reader);-- assertSameCount(reader, searcher, "long", numMatchingDocs);- assertSameCount(reader, searcher, "string", numMatchingDocs);- assertSameCount(reader, searcher, "doesNotExist", 0);-- // Test that we can't count in O(1) when there are deleted documents- w.w.getConfig().setMergePolicy(NoMergePolicy.INSTANCE);- w.deleteDocuments(LongPoint.newRangeQuery("long", 0L, 9L));- DirectoryReader reader2 = w.getReader();- final IndexSearcher searcher2 = new IndexSearcher(reader2);- final Query testQuery = new DocValuesFieldExistsQuery("long");- final Weight weight2 = searcher2.createWeight(testQuery, ScoreMode.COMPLETE, 1);- assertEquals(weight2.count(reader2.leaves().get(0)), -1);-- IOUtils.close(reader, reader2, w, dir);- }-- private void assertSameCount(- IndexReader reader, IndexSearcher searcher, String field, int numMatchingDocs)- throws IOException {- final Query testQuery = new DocValuesFieldExistsQuery(field);- assertEquals(searcher.count(testQuery), numMatchingDocs);- final Weight weight = searcher.createWeight(testQuery, ScoreMode.COMPLETE, 1);- assertEquals(weight.count(reader.leaves().get(0)), numMatchingDocs);- }-- private void assertSameMatches(IndexSearcher searcher, Query q1, Query q2, boolean scores)- throws IOException {- final int maxDoc = searcher.getIndexReader().maxDoc();- final TopDocs td1 = searcher.search(q1, maxDoc, scores ? Sort.RELEVANCE : Sort.INDEXORDER);- final TopDocs td2 = searcher.search(q2, maxDoc, scores ? Sort.RELEVANCE : Sort.INDEXORDER);- assertEquals(td1.totalHits.value, td2.totalHits.value);- for (int i = 0; i < td1.scoreDocs.length; ++i) {- assertEquals(td1.scoreDocs[i].doc, td2.scoreDocs[i].doc);- if (scores) {- assertEquals(td1.scoreDocs[i].score, td2.scoreDocs[i].score, 10e-7);- }- }- }-}diff --git a/lucene/core/src/test/org/apache/lucene/search/TestFieldExistsQuery.java b/lucene/core/src/test/org/apache/lucene/search/TestFieldExistsQuery.javanew file mode 100644index 00000000000..cbbccf35595--- /dev/null+++ b/lucene/core/src/test/org/apache/lucene/search/TestFieldExistsQuery.java@@ -0,0 +1,722 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package org.apache.lucene.search;++import java.io.IOException;+import org.apache.lucene.document.BinaryPoint;+import org.apache.lucene.document.Document;+import org.apache.lucene.document.DoubleDocValuesField;+import org.apache.lucene.document.Field;+import org.apache.lucene.document.Field.Store;+import org.apache.lucene.document.FieldType;+import org.apache.lucene.document.KnnVectorField;+import org.apache.lucene.document.LongPoint;+import org.apache.lucene.document.NumericDocValuesField;+import org.apache.lucene.document.SortedDocValuesField;+import org.apache.lucene.document.SortedNumericDocValuesField;+import org.apache.lucene.document.StringField;+import org.apache.lucene.document.TextField;+import org.apache.lucene.index.DirectoryReader;+import org.apache.lucene.index.IndexOptions;+import org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.NoMergePolicy;+import org.apache.lucene.index.Term;+import org.apache.lucene.search.BooleanClause.Occur;+import org.apache.lucene.store.Directory;+import org.apache.lucene.tests.index.RandomIndexWriter;+import org.apache.lucene.tests.util.LuceneTestCase;+import org.apache.lucene.tests.util.TestUtil;+import org.apache.lucene.util.BytesRef;+import org.apache.lucene.util.IOUtils;+import org.apache.lucene.util.VectorUtil;++public class TestFieldExistsQuery extends LuceneTestCase {++ public void testDocValuesRewriteWithTermsPresent() throws IOException {+ Directory dir = newDirectory();+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir);+ final int numDocs = atLeast(100);+ for (int i = 0; i < numDocs; ++i) {+ Document doc = new Document();+ doc.add(new DoubleDocValuesField("f", 2.0));+ doc.add(new StringField("f", random().nextBoolean() ? "yes" : "no", Store.NO));+ iw.addDocument(doc);+ }+ iw.commit();+ final IndexReader reader = iw.getReader();+ iw.close();++ assertTrue((new FieldExistsQuery("f")).rewrite(reader) instanceof MatchAllDocsQuery);+ reader.close();+ dir.close();+ }++ public void testDocValuesRewriteWithPointValuesPresent() throws IOException {+ Directory dir = newDirectory();+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir);+ final int numDocs = atLeast(100);+ for (int i = 0; i < numDocs; ++i) {+ Document doc = new Document();+ doc.add(new BinaryPoint("dim", new byte[4], new byte[4]));+ doc.add(new DoubleDocValuesField("dim", 2.0));+ iw.addDocument(doc);+ }+ iw.commit();+ final IndexReader reader = iw.getReader();+ iw.close();++ assertTrue(new FieldExistsQuery("dim").rewrite(reader) instanceof MatchAllDocsQuery);+ reader.close();+ dir.close();+ }++ public void testDocValuesNoRewrite() throws IOException {+ Directory dir = newDirectory();+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir);+ final int numDocs = atLeast(100);+ for (int i = 0; i < numDocs; ++i) {+ Document doc = new Document();+ doc.add(new DoubleDocValuesField("dim", 2.0));+ doc.add(new BinaryPoint("dim", new byte[4], new byte[4]));+ iw.addDocument(doc);+ }+ for (int i = 0; i < numDocs; ++i) {+ Document doc = new Document();+ doc.add(new DoubleDocValuesField("f", 2.0));+ doc.add(new StringField("f", random().nextBoolean() ? "yes" : "no", Store.NO));+ iw.addDocument(doc);+ }+ iw.commit();+ final IndexReader reader = iw.getReader();+ iw.close();++ assertFalse((new FieldExistsQuery("dim")).rewrite(reader) instanceof MatchAllDocsQuery);+ assertFalse((new FieldExistsQuery("f")).rewrite(reader) instanceof MatchAllDocsQuery);+ reader.close();+ dir.close();+ }++ public void testDocValuesNoRewriteWithDocValues() throws IOException {+ Directory dir = newDirectory();+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir);+ final int numDocs = atLeast(100);+ for (int i = 0; i < numDocs; ++i) {+ Document doc = new Document();+ doc.add(new NumericDocValuesField("dv1", 1));+ doc.add(new SortedNumericDocValuesField("dv2", 1));+ doc.add(new SortedNumericDocValuesField("dv2", 2));+ iw.addDocument(doc);+ }+ iw.commit();+ final IndexReader reader = iw.getReader();+ iw.close();++ assertFalse((new FieldExistsQuery("dv1")).rewrite(reader) instanceof MatchAllDocsQuery);+ assertFalse((new FieldExistsQuery("dv2")).rewrite(reader) instanceof MatchAllDocsQuery);+ assertFalse((new FieldExistsQuery("dv3")).rewrite(reader) instanceof MatchAllDocsQuery);+ reader.close();+ dir.close();+ }++ public void testDocValuesRandom() throws IOException {+ final int iters = atLeast(10);+ for (int iter = 0; iter < iters; ++iter) {+ Directory dir = newDirectory();+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir);+ final int numDocs = atLeast(100);+ for (int i = 0; i < numDocs; ++i) {+ Document doc = new Document();+ final boolean hasValue = random().nextBoolean();+ if (hasValue) {+ doc.add(new NumericDocValuesField("dv1", 1));+ doc.add(new SortedNumericDocValuesField("dv2", 1));+ doc.add(new SortedNumericDocValuesField("dv2", 2));+ doc.add(new StringField("has_value", "yes", Store.NO));+ }+ doc.add(new StringField("f", random().nextBoolean() ? "yes" : "no", Store.NO));+ iw.addDocument(doc);+ }+ if (random().nextBoolean()) {+ iw.deleteDocuments(new TermQuery(new Term("f", "no")));+ }+ iw.commit();+ final IndexReader reader = iw.getReader();+ final IndexSearcher searcher = newSearcher(reader);+ iw.close();++ assertSameMatches(+ searcher,+ new TermQuery(new Term("has_value", "yes")),+ new FieldExistsQuery("dv1"),+ false);+ assertSameMatches(+ searcher,+ new TermQuery(new Term("has_value", "yes")),+ new FieldExistsQuery("dv2"),+ false);++ reader.close();+ dir.close();+ }+ }++ public void testDocValuesApproximation() throws IOException {+ final int iters = atLeast(10);+ for (int iter = 0; iter < iters; ++iter) {+ Directory dir = newDirectory();+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir);+ final int numDocs = atLeast(100);+ for (int i = 0; i < numDocs; ++i) {+ Document doc = new Document();+ final boolean hasValue = random().nextBoolean();+ if (hasValue) {+ doc.add(new NumericDocValuesField("dv1", 1));+ doc.add(new SortedNumericDocValuesField("dv2", 1));+ doc.add(new SortedNumericDocValuesField("dv2", 2));+ doc.add(new StringField("has_value", "yes", Store.NO));+ }+ doc.add(new StringField("f", random().nextBoolean() ? "yes" : "no", Store.NO));+ iw.addDocument(doc);+ }+ if (random().nextBoolean()) {+ iw.deleteDocuments(new TermQuery(new Term("f", "no")));+ }+ iw.commit();+ final IndexReader reader = iw.getReader();+ final IndexSearcher searcher = newSearcher(reader);+ iw.close();++ BooleanQuery.Builder ref = new BooleanQuery.Builder();+ ref.add(new TermQuery(new Term("f", "yes")), Occur.MUST);+ ref.add(new TermQuery(new Term("has_value", "yes")), Occur.FILTER);++ BooleanQuery.Builder bq1 = new BooleanQuery.Builder();+ bq1.add(new TermQuery(new Term("f", "yes")), Occur.MUST);+ bq1.add(new FieldExistsQuery("dv1"), Occur.FILTER);+ assertSameMatches(searcher, ref.build(), bq1.build(), true);++ BooleanQuery.Builder bq2 = new BooleanQuery.Builder();+ bq2.add(new TermQuery(new Term("f", "yes")), Occur.MUST);+ bq2.add(new FieldExistsQuery("dv2"), Occur.FILTER);+ assertSameMatches(searcher, ref.build(), bq2.build(), true);++ reader.close();+ dir.close();+ }+ }++ public void testDocValuesScore() throws IOException {+ final int iters = atLeast(10);+ for (int iter = 0; iter < iters; ++iter) {+ Directory dir = newDirectory();+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir);+ final int numDocs = atLeast(100);+ for (int i = 0; i < numDocs; ++i) {+ Document doc = new Document();+ final boolean hasValue = random().nextBoolean();+ if (hasValue) {+ doc.add(new NumericDocValuesField("dv1", 1));+ doc.add(new SortedNumericDocValuesField("dv2", 1));+ doc.add(new SortedNumericDocValuesField("dv2", 2));+ doc.add(new StringField("has_value", "yes", Store.NO));+ }+ doc.add(new StringField("f", random().nextBoolean() ? "yes" : "no", Store.NO));+ iw.addDocument(doc);+ }+ if (random().nextBoolean()) {+ iw.deleteDocuments(new TermQuery(new Term("f", "no")));+ }+ iw.commit();+ final IndexReader reader = iw.getReader();+ final IndexSearcher searcher = newSearcher(reader);+ iw.close();++ final float boost = random().nextFloat() * 10;+ final Query ref =+ new BoostQuery(+ new ConstantScoreQuery(new TermQuery(new Term("has_value", "yes"))), boost);++ final Query q1 = new BoostQuery(new FieldExistsQuery("dv1"), boost);+ assertSameMatches(searcher, ref, q1, true);++ final Query q2 = new BoostQuery(new FieldExistsQuery("dv2"), boost);+ assertSameMatches(searcher, ref, q2, true);++ reader.close();+ dir.close();+ }+ }++ public void testDocValuesMissingField() throws IOException {+ Directory dir = newDirectory();+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir);+ iw.addDocument(new Document());+ iw.commit();+ final IndexReader reader = iw.getReader();+ final IndexSearcher searcher = newSearcher(reader);+ iw.close();+ assertEquals(0, searcher.count(new FieldExistsQuery("f")));+ reader.close();+ dir.close();+ }++ public void testDocValuesAllDocsHaveField() throws IOException {+ Directory dir = newDirectory();+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir);+ Document doc = new Document();+ doc.add(new NumericDocValuesField("f", 1));+ iw.addDocument(doc);+ iw.commit();+ final IndexReader reader = iw.getReader();+ final IndexSearcher searcher = newSearcher(reader);+ iw.close();+ assertEquals(1, searcher.count(new FieldExistsQuery("f")));+ reader.close();+ dir.close();+ }++ public void testDocValuesFieldExistsButNoDocsHaveField() throws IOException {+ Directory dir = newDirectory();+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir);+ // 1st segment has the field, but 2nd one does not+ Document doc = new Document();+ doc.add(new NumericDocValuesField("f", 1));+ iw.addDocument(doc);+ iw.commit();+ iw.addDocument(new Document());+ iw.commit();+ final IndexReader reader = iw.getReader();+ final IndexSearcher searcher = newSearcher(reader);+ iw.close();+ assertEquals(1, searcher.count(new FieldExistsQuery("f")));+ reader.close();+ dir.close();+ }++ public void testDocValuesQueryMatchesCount() throws IOException {+ Directory dir = newDirectory();+ RandomIndexWriter w = new RandomIndexWriter(random(), dir);++ int randomNumDocs = TestUtil.nextInt(random(), 11, 100);+ int numMatchingDocs = 0;++ for (int i = 0; i < randomNumDocs; i++) {+ Document doc = new Document();+ // We select most documents randomly but keep two documents:+ // * #0 ensures we will delete at least one document (with long between 0 and 9)+ // * #10 ensures we will keep at least one document (with long greater than 9)+ if (i == 0 || i == 10 || random().nextBoolean()) {+ doc.add(new LongPoint("long", i));+ doc.add(new NumericDocValuesField("long", i));+ doc.add(new StringField("string", "value", Store.NO));+ doc.add(new SortedDocValuesField("string", new BytesRef("value")));+ numMatchingDocs++;+ }+ w.addDocument(doc);+ }+ w.forceMerge(1);++ DirectoryReader reader = w.getReader();+ final IndexSearcher searcher = new IndexSearcher(reader);++ assertSameCount(reader, searcher, "long", numMatchingDocs);+ assertSameCount(reader, searcher, "string", numMatchingDocs);+ assertSameCount(reader, searcher, "doesNotExist", 0);++ // Test that we can't count in O(1) when there are deleted documents+ w.w.getConfig().setMergePolicy(NoMergePolicy.INSTANCE);+ w.deleteDocuments(LongPoint.newRangeQuery("long", 0L, 9L));+ DirectoryReader reader2 = w.getReader();+ final IndexSearcher searcher2 = new IndexSearcher(reader2);+ final Query testQuery = new FieldExistsQuery("long");+ final Weight weight2 = searcher2.createWeight(testQuery, ScoreMode.COMPLETE, 1);+ assertEquals(weight2.count(reader2.leaves().get(0)), -1);++ IOUtils.close(reader, reader2, w, dir);+ }++ public void testNormsRandom() throws IOException {+ final int iters = atLeast(10);+ for (int iter = 0; iter < iters; ++iter) {+ Directory dir = newDirectory();+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir);+ final int numDocs = atLeast(100);+ for (int i = 0; i < numDocs; ++i) {+ Document doc = new Document();+ final boolean hasValue = random().nextBoolean();+ if (hasValue) {+ doc.add(new TextField("text1", "value", Store.NO));+ doc.add(new StringField("has_value", "yes", Store.NO));+ }+ doc.add(new StringField("f", random().nextBoolean() ? "yes" : "no", Store.NO));+ iw.addDocument(doc);+ }+ if (random().nextBoolean()) {+ iw.deleteDocuments(new TermQuery(new Term("f", "no")));+ }+ iw.commit();+ final IndexReader reader = iw.getReader();+ final IndexSearcher searcher = newSearcher(reader);+ iw.close();++ assertSameMatches(+ searcher,+ new TermQuery(new Term("has_value", "yes")),+ new FieldExistsQuery("text1"),+ false);++ reader.close();+ dir.close();+ }+ }++ public void testNormsApproximation() throws IOException {+ final int iters = atLeast(10);+ for (int iter = 0; iter < iters; ++iter) {+ Directory dir = newDirectory();+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir);+ final int numDocs = atLeast(100);+ for (int i = 0; i < numDocs; ++i) {+ Document doc = new Document();+ final boolean hasValue = random().nextBoolean();+ if (hasValue) {+ doc.add(new TextField("text1", "value", Store.NO));+ doc.add(new StringField("has_value", "yes", Store.NO));+ }+ doc.add(new StringField("f", random().nextBoolean() ? "yes" : "no", Store.NO));+ iw.addDocument(doc);+ }+ if (random().nextBoolean()) {+ iw.deleteDocuments(new TermQuery(new Term("f", "no")));+ }+ iw.commit();+ final IndexReader reader = iw.getReader();+ final IndexSearcher searcher = newSearcher(reader);+ iw.close();++ BooleanQuery.Builder ref = new BooleanQuery.Builder();+ ref.add(new TermQuery(new Term("f", "yes")), Occur.MUST);+ ref.add(new TermQuery(new Term("has_value", "yes")), Occur.FILTER);++ BooleanQuery.Builder bq1 = new BooleanQuery.Builder();+ bq1.add(new TermQuery(new Term("f", "yes")), Occur.MUST);+ bq1.add(new FieldExistsQuery("text1"), Occur.FILTER);+ assertSameMatches(searcher, ref.build(), bq1.build(), true);++ reader.close();+ dir.close();+ }+ }++ public void testNormsScore() throws IOException {+ final int iters = atLeast(10);+ for (int iter = 0; iter < iters; ++iter) {+ Directory dir = newDirectory();+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir);+ final int numDocs = atLeast(100);+ for (int i = 0; i < numDocs; ++i) {+ Document doc = new Document();+ final boolean hasValue = random().nextBoolean();+ if (hasValue) {+ doc.add(new TextField("text1", "value", Store.NO));+ doc.add(new StringField("has_value", "yes", Store.NO));+ }+ doc.add(new StringField("f", random().nextBoolean() ? "yes" : "no", Store.NO));+ iw.addDocument(doc);+ }+ if (random().nextBoolean()) {+ iw.deleteDocuments(new TermQuery(new Term("f", "no")));+ }+ iw.commit();+ final IndexReader reader = iw.getReader();+ final IndexSearcher searcher = newSearcher(reader);+ iw.close();++ final float boost = random().nextFloat() * 10;+ final Query ref =+ new BoostQuery(+ new ConstantScoreQuery(new TermQuery(new Term("has_value", "yes"))), boost);++ final Query q1 = new BoostQuery(new FieldExistsQuery("text1"), boost);+ assertSameMatches(searcher, ref, q1, true);++ reader.close();+ dir.close();+ }+ }++ public void testNormsMissingField() throws IOException {+ Directory dir = newDirectory();+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir);+ iw.addDocument(new Document());+ iw.commit();+ final IndexReader reader = iw.getReader();+ final IndexSearcher searcher = newSearcher(reader);+ iw.close();+ assertEquals(0, searcher.count(new FieldExistsQuery("f")));+ reader.close();+ dir.close();+ }++ public void testNormsAllDocsHaveField() throws IOException {+ Directory dir = newDirectory();+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir);+ Document doc = new Document();+ doc.add(new TextField("f", "value", Store.NO));+ iw.addDocument(doc);+ iw.commit();+ final IndexReader reader = iw.getReader();+ final IndexSearcher searcher = newSearcher(reader);+ iw.close();+ assertEquals(1, searcher.count(new FieldExistsQuery("f")));+ reader.close();+ dir.close();+ }++ public void testNormsFieldExistsButNoDocsHaveField() throws IOException {+ Directory dir = newDirectory();+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir);+ // 1st segment has the field, but 2nd one does not+ Document doc = new Document();+ doc.add(new TextField("f", "value", Store.NO));+ iw.addDocument(doc);+ iw.commit();+ iw.addDocument(new Document());+ iw.commit();+ final IndexReader reader = iw.getReader();+ final IndexSearcher searcher = newSearcher(reader);+ iw.close();+ assertEquals(1, searcher.count(new FieldExistsQuery("f")));+ reader.close();+ dir.close();+ }++ public void testNormsQueryMatchesCount() throws IOException {+ Directory dir = newDirectory();+ RandomIndexWriter w = new RandomIndexWriter(random(), dir);++ int randomNumDocs = TestUtil.nextInt(random(), 10, 100);++ FieldType noNormsFieldType = new FieldType();+ noNormsFieldType.setOmitNorms(true);+ noNormsFieldType.setIndexOptions(IndexOptions.DOCS);++ Document doc = new Document();+ doc.add(new TextField("text", "always here", Store.NO));+ doc.add(new TextField("text_s", "", Store.NO));+ doc.add(new Field("text_n", "always here", noNormsFieldType));+ w.addDocument(doc);++ for (int i = 1; i < randomNumDocs; i++) {+ doc.clear();+ doc.add(new TextField("text", "some text", Store.NO));+ doc.add(new TextField("text_s", "some text", Store.NO));+ doc.add(new Field("text_n", "some here", noNormsFieldType));+ w.addDocument(doc);+ }+ w.forceMerge(1);++ DirectoryReader reader = w.getReader();+ final IndexSearcher searcher = new IndexSearcher(reader);++ assertNormsCountWithShortcut(searcher, "text", randomNumDocs);+ assertNormsCountWithShortcut(searcher, "doesNotExist", 0);+ expectThrows(IllegalStateException.class, () -> searcher.count(new FieldExistsQuery("text_n")));++ // docs that have a text field that analyzes to an empty token+ // stream still have a recorded norm value but don't show up in+ // Reader.getDocCount(field), so we can't use the shortcut for+ // these fields+ assertNormsCountWithoutShortcut(searcher, "text_s", randomNumDocs);++ // We can still shortcut with deleted docs+ w.w.getConfig().setMergePolicy(NoMergePolicy.INSTANCE);+ w.deleteDocuments(new Term("text", "text")); // deletes all but the first doc+ DirectoryReader reader2 = w.getReader();+ final IndexSearcher searcher2 = new IndexSearcher(reader2);+ assertNormsCountWithShortcut(searcher2, "text", 1);++ IOUtils.close(reader, reader2, w, dir);+ }++ private void assertNormsCountWithoutShortcut(+ IndexSearcher searcher, String field, int expectedCount) throws IOException {+ final Query q = new FieldExistsQuery(field);+ final Weight weight = searcher.createWeight(q, ScoreMode.COMPLETE, 1);+ assertEquals(-1, weight.count(searcher.reader.leaves().get(0)));+ assertEquals(expectedCount, searcher.count(q));+ }++ private void assertNormsCountWithShortcut(+ IndexSearcher searcher, String field, int numMatchingDocs) throws IOException {+ final Query testQuery = new FieldExistsQuery(field);+ assertEquals(numMatchingDocs, searcher.count(testQuery));+ final Weight weight = searcher.createWeight(testQuery, ScoreMode.COMPLETE, 1);+ assertEquals(numMatchingDocs, weight.count(searcher.reader.leaves().get(0)));+ }++ public void testKnnVectorRandom() throws IOException {+ int iters = atLeast(10);+ for (int iter = 0; iter < iters; ++iter) {+ try (Directory dir = newDirectory();+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir)) {+ int numDocs = atLeast(100);+ for (int i = 0; i < numDocs; ++i) {+ Document doc = new Document();+ boolean hasValue = random().nextBoolean();+ if (hasValue) {+ doc.add(new KnnVectorField("vector", randomVector(5)));+ doc.add(new StringField("has_value", "yes", Store.NO));+ }+ doc.add(new StringField("field", "value", Store.NO));+ iw.addDocument(doc);+ }+ if (random().nextBoolean()) {+ iw.deleteDocuments(new TermQuery(new Term("f", "no")));+ }+ iw.commit();++ try (IndexReader reader = iw.getReader()) {+ IndexSearcher searcher = newSearcher(reader);++ assertSameMatches(+ searcher,+ new TermQuery(new Term("has_value", "yes")),+ new FieldExistsQuery("vector"),+ false);++ float boost = random().nextFloat() * 10;+ assertSameMatches(+ searcher,+ new BoostQuery(+ new ConstantScoreQuery(new TermQuery(new Term("has_value", "yes"))), boost),+ new BoostQuery(new FieldExistsQuery("vector"), boost),+ true);+ }+ }+ }+ }++ public void testKnnVectorMissingField() throws IOException {+ try (Directory dir = newDirectory();+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir)) {+ iw.addDocument(new Document());+ iw.commit();+ try (IndexReader reader = iw.getReader()) {+ IndexSearcher searcher = newSearcher(reader);+ assertEquals(0, searcher.count(new FieldExistsQuery("f")));+ }+ }+ }++ public void testKnnVectorAllDocsHaveField() throws IOException {+ try (Directory dir = newDirectory();+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir)) {+ Document doc = new Document();+ doc.add(new KnnVectorField("vector", randomVector(3)));+ iw.addDocument(doc);+ iw.commit();+ try (IndexReader reader = iw.getReader()) {+ IndexSearcher searcher = newSearcher(reader);+ assertEquals(1, searcher.count(new FieldExistsQuery("vector")));+ }+ }+ }++ public void testKnnVectorConjunction() throws IOException {+ try (Directory dir = newDirectory();+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir)) {+ int numDocs = atLeast(100);+ int numVectors = 0;++ boolean allDocsHaveVector = random().nextBoolean();+ for (int i = 0; i < numDocs; ++i) {+ Document doc = new Document();+ if (allDocsHaveVector || random().nextBoolean()) {+ doc.add(new KnnVectorField("vector", randomVector(5)));+ numVectors++;+ }+ doc.add(new StringField("field", "value" + (i % 2), Store.NO));+ iw.addDocument(doc);+ }+ try (IndexReader reader = iw.getReader()) {+ IndexSearcher searcher = newSearcher(reader);+ Occur occur = random().nextBoolean() ? Occur.MUST : Occur.FILTER;+ BooleanQuery booleanQuery =+ new BooleanQuery.Builder()+ .add(new TermQuery(new Term("field", "value1")), occur)+ .add(new FieldExistsQuery("vector"), Occur.FILTER)+ .build();++ int count = searcher.count(booleanQuery);+ assertTrue(count <= numVectors);+ if (allDocsHaveVector) {+ assertEquals(numDocs / 2, count);+ }+ }+ }+ }++ public void testKnnVectorFieldExistsButNoDocsHaveField() throws IOException {+ try (Directory dir = newDirectory();+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir)) {+ // 1st segment has the field, but 2nd one does not+ Document doc = new Document();+ doc.add(new KnnVectorField("vector", randomVector(3)));+ iw.addDocument(doc);+ iw.commit();+ iw.addDocument(new Document());+ iw.commit();+ try (IndexReader reader = iw.getReader()) {+ IndexSearcher searcher = newSearcher(reader);+ assertEquals(1, searcher.count(new FieldExistsQuery("vector")));+ }+ }+ }++ private float[] randomVector(int dim) {+ float[] v = new float[dim];+ for (int i = 0; i < dim; i++) {+ v[i] = random().nextFloat();+ }+ VectorUtil.l2normalize(v);+ return v;+ }++ private void assertSameMatches(IndexSearcher searcher, Query q1, Query q2, boolean scores)+ throws IOException {+ final int maxDoc = searcher.getIndexReader().maxDoc();+ final TopDocs td1 = searcher.search(q1, maxDoc, scores ? Sort.RELEVANCE : Sort.INDEXORDER);+ final TopDocs td2 = searcher.search(q2, maxDoc, scores ? Sort.RELEVANCE : Sort.INDEXORDER);+ assertEquals(td1.totalHits.value, td2.totalHits.value);+ for (int i = 0; i < td1.scoreDocs.length; ++i) {+ assertEquals(td1.scoreDocs[i].doc, td2.scoreDocs[i].doc);+ if (scores) {+ assertEquals(td1.scoreDocs[i].score, td2.scoreDocs[i].score, 10e-7);+ }+ }+ }++ private void assertSameCount(+ IndexReader reader, IndexSearcher searcher, String field, int numMatchingDocs)+ throws IOException {+ final Query testQuery = new FieldExistsQuery(field);+ assertEquals(searcher.count(testQuery), numMatchingDocs);+ final Weight weight = searcher.createWeight(testQuery, ScoreMode.COMPLETE, 1);+ assertEquals(weight.count(reader.leaves().get(0)), numMatchingDocs);+ }+}diff --git a/lucene/core/src/test/org/apache/lucene/search/TestKnnVectorFieldExistsQuery.java b/lucene/core/src/test/org/apache/lucene/search/TestKnnVectorFieldExistsQuery.javadeleted file mode 100644index 3444ecab119..00000000000--- a/lucene/core/src/test/org/apache/lucene/search/TestKnnVectorFieldExistsQuery.java+++ /dev/null@@ -1,175 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-package org.apache.lucene.search;--import java.io.IOException;-import org.apache.lucene.document.Document;-import org.apache.lucene.document.Field.Store;-import org.apache.lucene.document.KnnVectorField;-import org.apache.lucene.document.StringField;-import org.apache.lucene.index.IndexReader;-import org.apache.lucene.index.Term;-import org.apache.lucene.search.BooleanClause.Occur;-import org.apache.lucene.store.Directory;-import org.apache.lucene.tests.index.RandomIndexWriter;-import org.apache.lucene.tests.util.LuceneTestCase;-import org.apache.lucene.util.VectorUtil;--public class TestKnnVectorFieldExistsQuery extends LuceneTestCase {-- public void testRandom() throws IOException {- int iters = atLeast(10);- for (int iter = 0; iter < iters; ++iter) {- try (Directory dir = newDirectory();- RandomIndexWriter iw = new RandomIndexWriter(random(), dir)) {- int numDocs = atLeast(100);- for (int i = 0; i < numDocs; ++i) {- Document doc = new Document();- boolean hasValue = random().nextBoolean();- if (hasValue) {- doc.add(new KnnVectorField("vector", randomVector(5)));- doc.add(new StringField("has_value", "yes", Store.NO));- }- doc.add(new StringField("field", "value", Store.NO));- iw.addDocument(doc);- }- if (random().nextBoolean()) {- iw.deleteDocuments(new TermQuery(new Term("f", "no")));- }- iw.commit();-- try (IndexReader reader = iw.getReader()) {- IndexSearcher searcher = newSearcher(reader);-- assertSameMatches(- searcher,- new TermQuery(new Term("has_value", "yes")),- new KnnVectorFieldExistsQuery("vector"),- false);-- float boost = random().nextFloat() * 10;- assertSameMatches(- searcher,- new BoostQuery(- new ConstantScoreQuery(new TermQuery(new Term("has_value", "yes"))), boost),- new BoostQuery(new KnnVectorFieldExistsQuery("vector"), boost),- true);- }- }- }- }-- public void testMissingField() throws IOException {- try (Directory dir = newDirectory();- RandomIndexWriter iw = new RandomIndexWriter(random(), dir)) {- iw.addDocument(new Document());- iw.commit();- try (IndexReader reader = iw.getReader()) {- IndexSearcher searcher = newSearcher(reader);- assertEquals(0, searcher.count(new KnnVectorFieldExistsQuery("f")));- }- }- }-- public void testAllDocsHaveField() throws IOException {- try (Directory dir = newDirectory();- RandomIndexWriter iw = new RandomIndexWriter(random(), dir)) {- Document doc = new Document();- doc.add(new KnnVectorField("vector", randomVector(3)));- iw.addDocument(doc);- iw.commit();- try (IndexReader reader = iw.getReader()) {- IndexSearcher searcher = newSearcher(reader);- assertEquals(1, searcher.count(new KnnVectorFieldExistsQuery("vector")));- }- }- }-- public void testConjunction() throws IOException {- try (Directory dir = newDirectory();- RandomIndexWriter iw = new RandomIndexWriter(random(), dir)) {- int numDocs = atLeast(100);- int numVectors = 0;-- boolean allDocsHaveVector = random().nextBoolean();- for (int i = 0; i < numDocs; ++i) {- Document doc = new Document();- if (allDocsHaveVector || random().nextBoolean()) {- doc.add(new KnnVectorField("vector", randomVector(5)));- numVectors++;- }- doc.add(new StringField("field", "value" + (i % 2), Store.NO));- iw.addDocument(doc);- }- try (IndexReader reader = iw.getReader()) {- IndexSearcher searcher = newSearcher(reader);- Occur occur = random().nextBoolean() ? Occur.MUST : Occur.FILTER;- BooleanQuery booleanQuery =- new BooleanQuery.Builder()- .add(new TermQuery(new Term("field", "value1")), occur)- .add(new KnnVectorFieldExistsQuery("vector"), Occur.FILTER)- .build();-- int count = searcher.count(booleanQuery);- assertTrue(count <= numVectors);- if (allDocsHaveVector) {- assertEquals(numDocs / 2, count);- }- }- }- }-- public void testFieldExistsButNoDocsHaveField() throws IOException {- try (Directory dir = newDirectory();- RandomIndexWriter iw = new RandomIndexWriter(random(), dir)) {- // 1st segment has the field, but 2nd one does not- Document doc = new Document();- doc.add(new KnnVectorField("vector", randomVector(3)));- iw.addDocument(doc);- iw.commit();- iw.addDocument(new Document());- iw.commit();- try (IndexReader reader = iw.getReader()) {- IndexSearcher searcher = newSearcher(reader);- assertEquals(1, searcher.count(new KnnVectorFieldExistsQuery("vector")));- }- }- }-- private float[] randomVector(int dim) {- float[] v = new float[dim];- for (int i = 0; i < dim; i++) {- v[i] = random().nextFloat();- }- VectorUtil.l2normalize(v);- return v;- }-- private void assertSameMatches(IndexSearcher searcher, Query q1, Query q2, boolean scores)- throws IOException {- final int maxDoc = searcher.getIndexReader().maxDoc();- final TopDocs td1 = searcher.search(q1, maxDoc, scores ? Sort.RELEVANCE : Sort.INDEXORDER);- final TopDocs td2 = searcher.search(q2, maxDoc, scores ? Sort.RELEVANCE : Sort.INDEXORDER);- assertEquals(td1.totalHits.value, td2.totalHits.value);- for (int i = 0; i < td1.scoreDocs.length; ++i) {- assertEquals(td1.scoreDocs[i].doc, td2.scoreDocs[i].doc);- if (scores) {- assertEquals(td1.scoreDocs[i].score, td2.scoreDocs[i].score, 10e-7);- }- }- }-}diff --git a/lucene/core/src/test/org/apache/lucene/search/TestNormsFieldExistsQuery.java b/lucene/core/src/test/org/apache/lucene/search/TestNormsFieldExistsQuery.javadeleted file mode 100644index cb5da03134c..00000000000--- a/lucene/core/src/test/org/apache/lucene/search/TestNormsFieldExistsQuery.java+++ /dev/null@@ -1,273 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-package org.apache.lucene.search;--import java.io.IOException;-import org.apache.lucene.document.Document;-import org.apache.lucene.document.Field;-import org.apache.lucene.document.Field.Store;-import org.apache.lucene.document.FieldType;-import org.apache.lucene.document.StringField;-import org.apache.lucene.document.TextField;-import org.apache.lucene.index.DirectoryReader;-import org.apache.lucene.index.IndexOptions;-import org.apache.lucene.index.IndexReader;-import org.apache.lucene.index.NoMergePolicy;-import org.apache.lucene.index.Term;-import org.apache.lucene.search.BooleanClause.Occur;-import org.apache.lucene.store.Directory;-import org.apache.lucene.tests.index.RandomIndexWriter;-import org.apache.lucene.tests.util.LuceneTestCase;-import org.apache.lucene.tests.util.TestUtil;-import org.apache.lucene.util.IOUtils;--public class TestNormsFieldExistsQuery extends LuceneTestCase {-- public void testRandom() throws IOException {- final int iters = atLeast(10);- for (int iter = 0; iter < iters; ++iter) {- Directory dir = newDirectory();- RandomIndexWriter iw = new RandomIndexWriter(random(), dir);- final int numDocs = atLeast(100);- for (int i = 0; i < numDocs; ++i) {- Document doc = new Document();- final boolean hasValue = random().nextBoolean();- if (hasValue) {- doc.add(new TextField("text1", "value", Store.NO));- doc.add(new StringField("has_value", "yes", Store.NO));- }- doc.add(new StringField("f", random().nextBoolean() ? "yes" : "no", Store.NO));- iw.addDocument(doc);- }- if (random().nextBoolean()) {- iw.deleteDocuments(new TermQuery(new Term("f", "no")));- }- iw.commit();- final IndexReader reader = iw.getReader();- final IndexSearcher searcher = newSearcher(reader);- iw.close();-- assertSameMatches(- searcher,- new TermQuery(new Term("has_value", "yes")),- new NormsFieldExistsQuery("text1"),- false);-- reader.close();- dir.close();- }- }-- public void testApproximation() throws IOException {- final int iters = atLeast(10);- for (int iter = 0; iter < iters; ++iter) {- Directory dir = newDirectory();- RandomIndexWriter iw = new RandomIndexWriter(random(), dir);- final int numDocs = atLeast(100);- for (int i = 0; i < numDocs; ++i) {- Document doc = new Document();- final boolean hasValue = random().nextBoolean();- if (hasValue) {- doc.add(new TextField("text1", "value", Store.NO));- doc.add(new StringField("has_value", "yes", Store.NO));- }- doc.add(new StringField("f", random().nextBoolean() ? "yes" : "no", Store.NO));- iw.addDocument(doc);- }- if (random().nextBoolean()) {- iw.deleteDocuments(new TermQuery(new Term("f", "no")));- }- iw.commit();- final IndexReader reader = iw.getReader();- final IndexSearcher searcher = newSearcher(reader);- iw.close();-- BooleanQuery.Builder ref = new BooleanQuery.Builder();- ref.add(new TermQuery(new Term("f", "yes")), Occur.MUST);- ref.add(new TermQuery(new Term("has_value", "yes")), Occur.FILTER);-- BooleanQuery.Builder bq1 = new BooleanQuery.Builder();- bq1.add(new TermQuery(new Term("f", "yes")), Occur.MUST);- bq1.add(new NormsFieldExistsQuery("text1"), Occur.FILTER);- assertSameMatches(searcher, ref.build(), bq1.build(), true);-- reader.close();- dir.close();- }- }-- public void testScore() throws IOException {- final int iters = atLeast(10);- for (int iter = 0; iter < iters; ++iter) {- Directory dir = newDirectory();- RandomIndexWriter iw = new RandomIndexWriter(random(), dir);- final int numDocs = atLeast(100);- for (int i = 0; i < numDocs; ++i) {- Document doc = new Document();- final boolean hasValue = random().nextBoolean();- if (hasValue) {- doc.add(new TextField("text1", "value", Store.NO));- doc.add(new StringField("has_value", "yes", Store.NO));- }- doc.add(new StringField("f", random().nextBoolean() ? "yes" : "no", Store.NO));- iw.addDocument(doc);- }- if (random().nextBoolean()) {- iw.deleteDocuments(new TermQuery(new Term("f", "no")));- }- iw.commit();- final IndexReader reader = iw.getReader();- final IndexSearcher searcher = newSearcher(reader);- iw.close();-- final float boost = random().nextFloat() * 10;- final Query ref =- new BoostQuery(- new ConstantScoreQuery(new TermQuery(new Term("has_value", "yes"))), boost);-- final Query q1 = new BoostQuery(new NormsFieldExistsQuery("text1"), boost);- assertSameMatches(searcher, ref, q1, true);-- reader.close();- dir.close();- }- }-- public void testMissingField() throws IOException {- Directory dir = newDirectory();- RandomIndexWriter iw = new RandomIndexWriter(random(), dir);- iw.addDocument(new Document());- iw.commit();- final IndexReader reader = iw.getReader();- final IndexSearcher searcher = newSearcher(reader);- iw.close();- assertEquals(0, searcher.count(new NormsFieldExistsQuery("f")));- reader.close();- dir.close();- }-- public void testAllDocsHaveField() throws IOException {- Directory dir = newDirectory();- RandomIndexWriter iw = new RandomIndexWriter(random(), dir);- Document doc = new Document();- doc.add(new TextField("f", "value", Store.NO));- iw.addDocument(doc);- iw.commit();- final IndexReader reader = iw.getReader();- final IndexSearcher searcher = newSearcher(reader);- iw.close();- assertEquals(1, searcher.count(new NormsFieldExistsQuery("f")));- reader.close();- dir.close();- }-- public void testFieldExistsButNoDocsHaveField() throws IOException {- Directory dir = newDirectory();- RandomIndexWriter iw = new RandomIndexWriter(random(), dir);- // 1st segment has the field, but 2nd one does not- Document doc = new Document();- doc.add(new TextField("f", "value", Store.NO));- iw.addDocument(doc);- iw.commit();- iw.addDocument(new Document());- iw.commit();- final IndexReader reader = iw.getReader();- final IndexSearcher searcher = newSearcher(reader);- iw.close();- assertEquals(1, searcher.count(new NormsFieldExistsQuery("f")));- reader.close();- dir.close();- }-- private void assertSameMatches(IndexSearcher searcher, Query q1, Query q2, boolean scores)- throws IOException {- final int maxDoc = searcher.getIndexReader().maxDoc();- final TopDocs td1 = searcher.search(q1, maxDoc, scores ? Sort.RELEVANCE : Sort.INDEXORDER);- final TopDocs td2 = searcher.search(q2, maxDoc, scores ? Sort.RELEVANCE : Sort.INDEXORDER);- assertEquals(td1.totalHits.value, td2.totalHits.value);- for (int i = 0; i < td1.scoreDocs.length; ++i) {- assertEquals(td1.scoreDocs[i].doc, td2.scoreDocs[i].doc);- if (scores) {- assertEquals(td1.scoreDocs[i].score, td2.scoreDocs[i].score, 10e-7);- }- }- }-- public void testQueryMatchesCount() throws IOException {- Directory dir = newDirectory();- RandomIndexWriter w = new RandomIndexWriter(random(), dir);-- int randomNumDocs = TestUtil.nextInt(random(), 10, 100);-- FieldType noNormsFieldType = new FieldType();- noNormsFieldType.setOmitNorms(true);- noNormsFieldType.setIndexOptions(IndexOptions.DOCS);-- Document doc = new Document();- doc.add(new TextField("text", "always here", Store.NO));- doc.add(new TextField("text_s", "", Store.NO));- doc.add(new Field("text_n", "always here", noNormsFieldType));- w.addDocument(doc);-- for (int i = 1; i < randomNumDocs; i++) {- doc.clear();- doc.add(new TextField("text", "some text", Store.NO));- doc.add(new TextField("text_s", "some text", Store.NO));- doc.add(new Field("text_n", "some here", noNormsFieldType));- w.addDocument(doc);- }- w.forceMerge(1);-- DirectoryReader reader = w.getReader();- final IndexSearcher searcher = new IndexSearcher(reader);-- assertCountWithShortcut(searcher, "text", randomNumDocs);- assertCountWithShortcut(searcher, "doesNotExist", 0);- assertCountWithShortcut(searcher, "text_n", 0);-- // docs that have a text field that analyzes to an empty token- // stream still have a recorded norm value but don't show up in- // Reader.getDocCount(field), so we can't use the shortcut for- // these fields- assertCountWithoutShortcut(searcher, "text_s", randomNumDocs);-- // We can still shortcut with deleted docs- w.w.getConfig().setMergePolicy(NoMergePolicy.INSTANCE);- w.deleteDocuments(new Term("text", "text")); // deletes all but the first doc- DirectoryReader reader2 = w.getReader();- final IndexSearcher searcher2 = new IndexSearcher(reader2);- assertCountWithShortcut(searcher2, "text", 1);-- IOUtils.close(reader, reader2, w, dir);- }-- private void assertCountWithoutShortcut(IndexSearcher searcher, String field, int expectedCount)- throws IOException {- final Query q = new NormsFieldExistsQuery(field);- final Weight weight = searcher.createWeight(q, ScoreMode.COMPLETE, 1);- assertEquals(-1, weight.count(searcher.reader.leaves().get(0)));- assertEquals(expectedCount, searcher.count(q));- }-- private void assertCountWithShortcut(IndexSearcher searcher, String field, int numMatchingDocs)- throws IOException {- final Query testQuery = new NormsFieldExistsQuery(field);- assertEquals(numMatchingDocs, searcher.count(testQuery));- final Weight weight = searcher.createWeight(testQuery, ScoreMode.COMPLETE, 1);- assertEquals(numMatchingDocs, weight.count(searcher.reader.leaves().get(0)));- }-}