Search in sources :

Example 81 with MatchAllDocsQuery

use of org.apache.lucene.search.MatchAllDocsQuery in project lucene-solr by apache.

the class TestBoostedQuery method testBasic.

public void testBasic() throws Exception {
    Query q = new MatchAllDocsQuery();
    TopDocs docs = is.search(q, 10);
    assertEquals(1, docs.totalHits);
    float score = docs.scoreDocs[0].score;
    Query boostedQ = new BoostedQuery(q, new ConstValueSource(2.0f));
    assertHits(boostedQ, new float[] { score * 2 });
}
Also used : TopDocs(org.apache.lucene.search.TopDocs) Query(org.apache.lucene.search.Query) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) ConstValueSource(org.apache.lucene.queries.function.valuesource.ConstValueSource) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery)

Example 82 with MatchAllDocsQuery

use of org.apache.lucene.search.MatchAllDocsQuery in project lucene-solr by apache.

the class SpatialExample method search.

private void search() throws Exception {
    IndexReader indexReader = DirectoryReader.open(directory);
    IndexSearcher indexSearcher = new IndexSearcher(indexReader);
    Sort idSort = new Sort(new SortField("id", SortField.Type.INT));
    //--Filter by circle (<= distance from a point)
    {
        //Search with circle
        //note: SpatialArgs can be parsed from a string
        SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects, ctx.makeCircle(-80.0, 33.0, DistanceUtils.dist2Degrees(200, DistanceUtils.EARTH_MEAN_RADIUS_KM)));
        Query query = strategy.makeQuery(args);
        TopDocs docs = indexSearcher.search(query, 10, idSort);
        assertDocMatchedIds(indexSearcher, docs, 2);
        //Now, lets get the distance for the 1st doc via computing from stored point value:
        // (this computation is usually not redundant)
        Document doc1 = indexSearcher.doc(docs.scoreDocs[0].doc);
        String doc1Str = doc1.getField(strategy.getFieldName()).stringValue();
        //assume doc1Str is "x y" as written in newSampleDocument()
        int spaceIdx = doc1Str.indexOf(' ');
        double x = Double.parseDouble(doc1Str.substring(0, spaceIdx));
        double y = Double.parseDouble(doc1Str.substring(spaceIdx + 1));
        double doc1DistDEG = ctx.calcDistance(args.getShape().getCenter(), x, y);
        assertEquals(121.6d, DistanceUtils.degrees2Dist(doc1DistDEG, DistanceUtils.EARTH_MEAN_RADIUS_KM), 0.1);
        //or more simply:
        assertEquals(121.6d, doc1DistDEG * DistanceUtils.DEG_TO_KM, 0.1);
    }
    //--Match all, order by distance ascending
    {
        Point pt = ctx.makePoint(60, -50);
        //the distance (in km)
        ValueSource valueSource = strategy.makeDistanceValueSource(pt, DistanceUtils.DEG_TO_KM);
        //false=asc dist
        Sort distSort = new Sort(valueSource.getSortField(false)).rewrite(indexSearcher);
        TopDocs docs = indexSearcher.search(new MatchAllDocsQuery(), 10, distSort);
        assertDocMatchedIds(indexSearcher, docs, 4, 20, 2);
    //To get the distance, we could compute from stored values like earlier.
    // However in this example we sorted on it, and the distance will get
    // computed redundantly.  If the distance is only needed for the top-X
    // search results then that's not a big deal. Alternatively, try wrapping
    // the ValueSource with CachingDoubleValueSource then retrieve the value
    // from the ValueSource now. See LUCENE-4541 for an example.
    }
    //demo arg parsing
    {
        SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects, ctx.makeCircle(-80.0, 33.0, 1));
        SpatialArgs args2 = new SpatialArgsParser().parse("Intersects(BUFFER(POINT(-80 33),1))", ctx);
        assertEquals(args.toString(), args2.toString());
    }
    indexReader.close();
}
Also used : IndexSearcher(org.apache.lucene.search.IndexSearcher) SpatialArgs(org.apache.lucene.spatial.query.SpatialArgs) Query(org.apache.lucene.search.Query) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) SpatialArgsParser(org.apache.lucene.spatial.query.SpatialArgsParser) SortField(org.apache.lucene.search.SortField) Point(org.locationtech.spatial4j.shape.Point) Document(org.apache.lucene.document.Document) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) TopDocs(org.apache.lucene.search.TopDocs) ValueSource(org.apache.lucene.queries.function.ValueSource) IndexReader(org.apache.lucene.index.IndexReader) Sort(org.apache.lucene.search.Sort)

Example 83 with MatchAllDocsQuery

use of org.apache.lucene.search.MatchAllDocsQuery in project lucene-solr by apache.

the class GeoFieldUpdater method create.

@Override
public DocTransformer create(String display, SolrParams params, SolrQueryRequest req) {
    String fname = params.get("f", display);
    if (fname.startsWith("[") && fname.endsWith("]")) {
        fname = display.substring(1, display.length() - 1);
    }
    SchemaField sf = req.getSchema().getFieldOrNull(fname);
    if (sf == null) {
        throw new SolrException(ErrorCode.BAD_REQUEST, this.getClass().getSimpleName() + " using unknown field: " + fname);
    }
    if (!(sf.getType() instanceof AbstractSpatialFieldType)) {
        throw new SolrException(ErrorCode.BAD_REQUEST, "GeoTransformer requested non-spatial field: " + fname + " (" + sf.getType().getClass().getSimpleName() + ")");
    }
    final GeoFieldUpdater updater = new GeoFieldUpdater();
    updater.field = fname;
    updater.display = display;
    updater.display_error = display + "_error";
    ValueSource shapes = null;
    AbstractSpatialFieldType<?> sdv = (AbstractSpatialFieldType<?>) sf.getType();
    SpatialStrategy strategy = sdv.getStrategy(fname);
    if (strategy instanceof CompositeSpatialStrategy) {
        shapes = ((CompositeSpatialStrategy) strategy).getGeometryStrategy().makeShapeValueSource();
    } else if (strategy instanceof SerializedDVStrategy) {
        shapes = ((SerializedDVStrategy) strategy).makeShapeValueSource();
    }
    String writerName = params.get("w", "GeoJSON");
    updater.formats = strategy.getSpatialContext().getFormats();
    updater.writer = updater.formats.getWriter(writerName);
    if (updater.writer == null) {
        StringBuilder str = new StringBuilder();
        str.append("Unknown Spatial Writer: ").append(writerName);
        str.append(" [");
        for (ShapeWriter w : updater.formats.getWriters()) {
            str.append(w.getFormatName()).append(' ');
        }
        str.append("]");
        throw new SolrException(ErrorCode.BAD_REQUEST, str.toString());
    }
    QueryResponseWriter qw = req.getCore().getQueryResponseWriter(req);
    updater.isJSON = (qw.getClass() == JSONResponseWriter.class) && (updater.writer instanceof GeoJSONWriter);
    // Using ValueSource
    if (shapes != null) {
        // we don't really need the qparser... just so we can reuse valueSource
        QParser parser = new QParser(null, null, params, req) {

            @Override
            public Query parse() throws SyntaxError {
                return new MatchAllDocsQuery();
            }
        };
        return new ValueSourceAugmenter(display, parser, shapes) {

            @Override
            protected void setValue(SolrDocument doc, Object val) {
                updater.setValue(doc, val);
            }
        };
    }
    // Using the raw stored values
    return new DocTransformer() {

        @Override
        public void transform(SolrDocument doc, int docid, float score) throws IOException {
            Object val = doc.remove(updater.field);
            if (val != null) {
                updater.setValue(doc, val);
            }
        }

        @Override
        public String getName() {
            return updater.display;
        }

        @Override
        public String[] getExtraRequestFields() {
            return new String[] { updater.field };
        }
    };
}
Also used : CompositeSpatialStrategy(org.apache.lucene.spatial.composite.CompositeSpatialStrategy) JSONResponseWriter(org.apache.solr.response.JSONResponseWriter) ShapeWriter(org.locationtech.spatial4j.io.ShapeWriter) AbstractSpatialFieldType(org.apache.solr.schema.AbstractSpatialFieldType) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) CompositeSpatialStrategy(org.apache.lucene.spatial.composite.CompositeSpatialStrategy) SpatialStrategy(org.apache.lucene.spatial.SpatialStrategy) SerializedDVStrategy(org.apache.lucene.spatial.serialized.SerializedDVStrategy) SchemaField(org.apache.solr.schema.SchemaField) SolrDocument(org.apache.solr.common.SolrDocument) ValueSource(org.apache.lucene.queries.function.ValueSource) QParser(org.apache.solr.search.QParser) QueryResponseWriter(org.apache.solr.response.QueryResponseWriter) GeoJSONWriter(org.locationtech.spatial4j.io.GeoJSONWriter) SolrException(org.apache.solr.common.SolrException)

Example 84 with MatchAllDocsQuery

use of org.apache.lucene.search.MatchAllDocsQuery in project lucene-solr by apache.

the class DistanceFacetsExample method search.

/** User runs a query and counts facets. */
public FacetResult search() throws IOException {
    FacetsCollector fc = new FacetsCollector();
    searcher.search(new MatchAllDocsQuery(), fc);
    Facets facets = new DoubleRangeFacetCounts("field", getDistanceValueSource(), fc, getBoundingBoxQuery(ORIGIN_LATITUDE, ORIGIN_LONGITUDE, 10.0), ONE_KM, TWO_KM, FIVE_KM, TEN_KM);
    return facets.getTopChildren(10, "field");
}
Also used : Facets(org.apache.lucene.facet.Facets) DoubleRangeFacetCounts(org.apache.lucene.facet.range.DoubleRangeFacetCounts) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) FacetsCollector(org.apache.lucene.facet.FacetsCollector)

Example 85 with MatchAllDocsQuery

use of org.apache.lucene.search.MatchAllDocsQuery in project lucene-solr by apache.

the class TestDemoExpressions method testStaticExtendedVariableExample.

public void testStaticExtendedVariableExample() throws Exception {
    Expression popularity = JavascriptCompiler.compile("doc[\"popularity\"].value");
    SimpleBindings bindings = new SimpleBindings();
    bindings.add("doc['popularity'].value", DoubleValuesSource.fromIntField("popularity"));
    Sort sort = new Sort(popularity.getSortField(bindings, true));
    TopFieldDocs td = searcher.search(new MatchAllDocsQuery(), 3, sort);
    FieldDoc d = (FieldDoc) td.scoreDocs[0];
    assertEquals(20D, (Double) d.fields[0], 1E-4);
    d = (FieldDoc) td.scoreDocs[1];
    assertEquals(5D, (Double) d.fields[0], 1E-4);
    d = (FieldDoc) td.scoreDocs[2];
    assertEquals(2D, (Double) d.fields[0], 1E-4);
}
Also used : FieldDoc(org.apache.lucene.search.FieldDoc) Sort(org.apache.lucene.search.Sort) TopFieldDocs(org.apache.lucene.search.TopFieldDocs) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery)

Aggregations

MatchAllDocsQuery (org.apache.lucene.search.MatchAllDocsQuery)288 IndexSearcher (org.apache.lucene.search.IndexSearcher)169 Directory (org.apache.lucene.store.Directory)133 Document (org.apache.lucene.document.Document)122 RandomIndexWriter (org.apache.lucene.index.RandomIndexWriter)122 IndexReader (org.apache.lucene.index.IndexReader)120 TopDocs (org.apache.lucene.search.TopDocs)91 Sort (org.apache.lucene.search.Sort)71 SortField (org.apache.lucene.search.SortField)64 Query (org.apache.lucene.search.Query)53 BooleanQuery (org.apache.lucene.search.BooleanQuery)50 TermQuery (org.apache.lucene.search.TermQuery)49 FacetsCollector (org.apache.lucene.facet.FacetsCollector)40 Facets (org.apache.lucene.facet.Facets)34 Term (org.apache.lucene.index.Term)33 ArrayList (java.util.ArrayList)32 DirectoryReader (org.apache.lucene.index.DirectoryReader)30 MappedFieldType (org.elasticsearch.index.mapper.MappedFieldType)28 SortedNumericDocValuesField (org.apache.lucene.document.SortedNumericDocValuesField)23 FacetResult (org.apache.lucene.facet.FacetResult)22