Example usage for org.apache.lucene.index DirectoryReader open

List of usage examples for org.apache.lucene.index DirectoryReader open

Introduction

In this page you can find the example usage for org.apache.lucene.index DirectoryReader open.

Prototype

public static DirectoryReader open(final IndexCommit commit, Map<String, String> readerAttributes)
        throws IOException 

Source Link

Document

Expert: returns an IndexReader reading the index in the given IndexCommit .

Usage

From source file:com.orientechnologies.lucene.tx.OLuceneTxChangesAbstract.java

License:Apache License

public IndexSearcher searcher() {
    // TODO optimize
    try {/*from  w  w w .  j  a  va 2s. com*/
        return new IndexSearcher(DirectoryReader.open(writer, true));
    } catch (IOException e) {
        OLogManager.instance().error(this, "Error during searcher instantiation", e);
    }

    return null;
}

From source file:com.orientechnologies.lucene.tx.OLuceneTxChangesAbstract.java

License:Apache License

@Override
public long deletedDocs(Query query, Filter filter) {

    try {//from   w  w  w  . ja  v  a2s .  c o m
        IndexSearcher indexSearcher = new IndexSearcher(DirectoryReader.open(deletedIdx, true));

        if (filter != null) {
            TopDocs search = indexSearcher.search(query, filter, Integer.MAX_VALUE);
            return search.totalHits;
        } else {
            TopDocs search = indexSearcher.search(query, Integer.MAX_VALUE);
            return search.totalHits;
        }
    } catch (IOException e) {
        OLogManager.instance().error(this, "Error during searcher instantiation", e);
    }

    return 0;
}

From source file:com.querydsl.lucene5.LuceneQueryTest.java

License:Apache License

@Test
@Ignore/*from  w  w  w.ja va2  s.c o m*/
// FIXME
public void Sorted_By_Different_Locales() throws Exception {
    Document d1 = new Document();
    Document d2 = new Document();
    Document d3 = new Document();
    d1.add(new TextField("sort", "a\u00c4", Store.YES));
    d2.add(new TextField("sort", "ab", Store.YES));
    d3.add(new TextField("sort", "aa", Store.YES));
    writer = createWriter(idx);
    writer.addDocument(d1);
    writer.addDocument(d2);
    writer.addDocument(d3);
    writer.close();

    IndexReader reader = DirectoryReader.open(writer, true);
    searcher = new IndexSearcher(reader);
    query = new LuceneQuery(new LuceneSerializer(true, true, Locale.ENGLISH), searcher);
    assertEquals(3, query.fetch().size());
    List<Document> results = query.where(sort.startsWith("a")).orderBy(sort.asc()).fetch();
    assertEquals(3, results.size());
    assertEquals("aa", results.get(0).getField("sort").stringValue());
    assertEquals("a\u00c4", results.get(1).getField("sort").stringValue());
    assertEquals("ab", results.get(2).getField("sort").stringValue());

    query = new LuceneQuery(new LuceneSerializer(true, true, new Locale("fi", "FI")), searcher);
    results = query.where(sort.startsWith("a")).orderBy(sort.asc()).fetch();
    assertEquals("aa", results.get(0).getField("sort").stringValue());
    assertEquals("ab", results.get(1).getField("sort").stringValue());
    assertEquals("a\u00c4", results.get(2).getField("sort").stringValue());
}

From source file:com.search.lucene.demo.facet.DistanceFacetsExample.java

License:Apache License

/** Build the example index. */
public void index() throws IOException {
    IndexWriter writer = new IndexWriter(indexDir,
            new IndexWriterConfig(new WhitespaceAnalyzer()).setOpenMode(OpenMode.CREATE));

    // TODO: we could index in radians instead ... saves all the conversions in getBoundingBoxFilter

    // Add documents with latitude/longitude location:
    // we index these both as DoubleFields (for bounding box/ranges) and as NumericDocValuesFields (for scoring)
    Document doc = new Document();
    doc.add(new DoubleField("latitude", 40.759011, Field.Store.NO));
    doc.add(new NumericDocValuesField("latitude", Double.doubleToRawLongBits(40.759011)));
    doc.add(new DoubleField("longitude", -73.9844722, Field.Store.NO));
    doc.add(new NumericDocValuesField("longitude", Double.doubleToRawLongBits(-73.9844722)));
    writer.addDocument(doc);//from w w  w .ja va 2 s  .  com

    doc = new Document();
    doc.add(new DoubleField("latitude", 40.718266, Field.Store.NO));
    doc.add(new NumericDocValuesField("latitude", Double.doubleToRawLongBits(40.718266)));
    doc.add(new DoubleField("longitude", -74.007819, Field.Store.NO));
    doc.add(new NumericDocValuesField("longitude", Double.doubleToRawLongBits(-74.007819)));
    writer.addDocument(doc);

    doc = new Document();
    doc.add(new DoubleField("latitude", 40.7051157, Field.Store.NO));
    doc.add(new NumericDocValuesField("latitude", Double.doubleToRawLongBits(40.7051157)));
    doc.add(new DoubleField("longitude", -74.0088305, Field.Store.NO));
    doc.add(new NumericDocValuesField("longitude", Double.doubleToRawLongBits(-74.0088305)));
    writer.addDocument(doc);

    // Open near-real-time searcher
    searcher = new IndexSearcher(DirectoryReader.open(writer, true));
    writer.close();
}

From source file:com.search.lucene.demo.facet.RangeFacetsExample.java

License:Apache License

/** Build the example index. */
public void index() throws IOException {
    IndexWriter indexWriter = new IndexWriter(indexDir,
            new IndexWriterConfig(new WhitespaceAnalyzer()).setOpenMode(OpenMode.CREATE));

    // Add documents with a fake timestamp, 1000 sec before
    // "now", 2000 sec before "now", ...:
    for (int i = 0; i < 100; i++) {
        Document doc = new Document();
        long then = nowSec - i * 1000;
        // Add as doc values field, so we can compute range facets:
        doc.add(new NumericDocValuesField("timestamp", then));
        // Add as numeric field so we can drill-down:
        doc.add(new LongField("timestamp", then, Field.Store.NO));
        indexWriter.addDocument(doc);//from   ww w .ja  v a  2 s.c o m
    }

    // Open near-real-time searcher
    searcher = new IndexSearcher(DirectoryReader.open(indexWriter, true));
    indexWriter.close();
}

From source file:com.util.Indexador.java

public List<Publicacion> buscarPublicaciones(String consulta)
        throws IOException, ParseException, java.text.ParseException {
    Publicacion obj;//from w w w.  j a v  a 2 s .co m
    List<Publicacion> listaPub;
    this.reader2 = DirectoryReader.open(this.writer2, true);
    this.searcher2 = new IndexSearcher(this.reader2);
    this.qp2 = new QueryParser(Version.LUCENE_41, "Contenido", analizador);
    this.qp2.setDefaultOperator(QueryParser.Operator.AND);
    Query query = this.qp2.parse(consulta);
    TopDocs docs = this.searcher2.search(query, 9999999);

    ScoreDoc[] score = docs.scoreDocs;
    Document dc = null;
    listaPub = new ArrayList<>();
    String[] arrTags = null;
    for (ScoreDoc sd1 : score) {
        obj = new Publicacion();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        dc = this.searcher2.doc(sd1.doc);
        obj.setCodPublicacion(Integer.parseInt(dc.get("codPublicacion")));
        obj.setTituloPub(dc.get("titulo"));
        obj.setImagenPub(dc.get("imagen"));
        obj.setF_creacionPub(DateTools.stringToDate(dc.get("f_publicacion")));
        obj.setN_likesPub(Integer.parseInt(dc.get("n_likes")));
        obj.setTagsPublicacion(dc.get("tags"));
        obj.getObjAlbum().setCodAlbum(Integer.parseInt(dc.get("codAlbum")));
        obj.getObjAlbum().setNombreAlb(dc.get("nombre"));
        obj.getObjAlbum().getObjCategoria().setCodCategoria(Integer.parseInt(dc.get("codCategoria")));
        obj.getObjAlbum().getObjCategoria().setNombreCategoria(dc.get("nombrecate"));
        obj.getObjAlbum().getObjPerfil().setCodPerfil(Integer.parseInt(dc.get("codPerfil")));
        obj.getObjAlbum().getObjPerfil().setNombrePer(dc.get("nombres"));
        obj.getObjAlbum().getObjPerfil().setApellidosPer(dc.get("apellidos"));
        obj.getObjAlbum().getObjPerfil().setImagenPer(dc.get("imagenper"));

        arrTags = new Utiles().SepararTags(obj.getTagsPublicacion());
        obj.setArrTags(arrTags);
        arrTags = null;
        listaPub.add(obj);
        obj = null;
    }

    this.writer2.deleteAll();
    this.writer2.close();

    return listaPub;

}

From source file:com.util.Indexador.java

public List<Perfil> buscarPerfiles(String consulta)
        throws IOException, ParseException, java.text.ParseException {
    Perfil obj;/*from  ww w  . ja v a 2 s  .c o m*/
    List<Perfil> listaPer;
    this.reader2 = DirectoryReader.open(this.writer2, true);
    this.searcher2 = new IndexSearcher(this.reader2);
    this.qp2 = new QueryParser(Version.LUCENE_41, "fullname", analizador);
    this.qp2.setDefaultOperator(QueryParser.Operator.AND);
    this.qp2.setAllowLeadingWildcard(true);
    Query query = this.qp2.parse(consulta + "*");
    TopDocs docs = this.searcher2.search(query, 4);

    ScoreDoc[] score = docs.scoreDocs;
    Document dc = null;
    listaPer = new ArrayList<>();
    for (ScoreDoc sd1 : score) {
        obj = new Perfil();
        dc = this.searcher2.doc(sd1.doc);
        obj.setCodPerfil(Integer.parseInt(dc.get("codPerfil")));
        obj.setNombrePer(dc.get("nombres"));
        obj.setApellidosPer(dc.get("apellidos"));
        obj.setImagenPer(dc.get("imagen"));
        if (dc.get("codDepartamento") != null) {
            obj.getObjDepartamento().setCodDepartamento(Integer.parseInt(dc.get("codDepartamento")));
        }
        if (dc.get("nombredep") != null) {
            obj.getObjDepartamento().setNombre_dep(dc.get("nombredep"));
        }
        listaPer.add(obj);
        obj = null;
    }

    this.writer2.deleteAll();
    this.writer2.close();

    return listaPer;

}

From source file:com.vmware.dcp.services.common.LuceneBlobIndexService.java

License:Open Source License

private IndexSearcher updateSearcher(String selfLink, IndexWriter w) throws IOException {
    IndexSearcher s = null;/*from w  w w.java 2  s  . c  om*/
    long now = Utils.getNowMicrosUtc();
    synchronized (this.searchSync) {
        s = this.searcher;
        if (s != null && this.searcherUpdateTimeMicros > this.indexUpdateTimeMicros) {
            return s;
        }
    }
    s = new IndexSearcher(DirectoryReader.open(w, true));
    synchronized (this.searchSync) {
        if (this.searcherUpdateTimeMicros < now) {
            this.searcher = s;
            this.searcherUpdateTimeMicros = now;
        }
        return this.searcher;
    }
}

From source file:com.vmware.dcp.services.common.LuceneDocumentIndexService.java

License:Open Source License

private void doSelfValidationQuery() throws Throwable {
    TermQuery tq = new TermQuery(new Term(ServiceDocument.FIELD_NAME_SELF_LINK, getSelfLink()));
    ServiceDocumentQueryResult rsp = new ServiceDocumentQueryResult();
    queryIndexWithWriter(Operation.createGet(getUri()), EnumSet.of(QueryOption.INCLUDE_ALL_VERSIONS), tq, null,
            null, Integer.MAX_VALUE, 0, null, rsp, ServiceOption.PERSISTENCE,
            new IndexSearcher(DirectoryReader.open(this.writer, true)));
}

From source file:com.vmware.dcp.services.common.LuceneDocumentIndexService.java

License:Open Source License

private IndexSearcher updateSearcher(String selfLink, int resultLimit, IndexWriter w) throws IOException {

    // We want avoid creating a new IndexSearcher, per query. So we create one in one of
    // following conditions:
    // 1) no searcher for this index exists
    // 2) the query is across many links or multiple version, not a specific one and index was
    // changed//w  ww . j a  va  2 s. c  om
    // 3) the query is for a specific self link AND the self link has seen an update after the
    // last query executed

    IndexSearcher s = null;
    boolean needNewSearcher = false;
    long now = Utils.getNowMicrosUtc();
    synchronized (this.searchSync) {
        s = this.searcher;

        if (s == null) {
            needNewSearcher = true;
        } else if (resultLimit > 1 && this.searcherUpdateTimeMicros < this.indexUpdateTimeMicros) {
            needNewSearcher = true;
        } else if (selfLink != null) {
            SelfLinkInfo sli = this.selfLinks.get(selfLink);
            if (sli != null) {
                needNewSearcher = sli.updateMicros > this.searcherUpdateTimeMicros;
            }
        }

        if (!needNewSearcher) {
            return this.searcher;
        }
    }

    // outside the lock create a new searcher. Another thread might race us and also create a
    // searcher, but that is OK, we will use the most recent one
    s = new IndexSearcher(DirectoryReader.open(w, true));

    if (hasOption(ServiceOption.INSTRUMENTATION)) {
        ServiceStat st = getStat(STAT_NAME_SEARCHER_UPDATE_COUNT);
        adjustStat(st, 1);
    }

    synchronized (this.searchSync) {
        if (this.searcherUpdateTimeMicros < now) {
            this.searcher = s;
            this.searcherUpdateTimeMicros = now;
        }
        return this.searcher;
    }
}