Example usage for org.apache.lucene.search IndexSearcher setSimilarity

List of usage examples for org.apache.lucene.search IndexSearcher setSimilarity

Introduction

In this page you can find the example usage for org.apache.lucene.search IndexSearcher setSimilarity.

Prototype

public void setSimilarity(Similarity similarity) 

Source Link

Document

Expert: Set the Similarity implementation used by this IndexSearcher.

Usage

From source file:de.unihildesheim.iw.lucene.index.IndexUtils.java

License:Open Source License

/**
 * Get an {@link IndexSearcher} instance. If the reader is an instance of
 * {@link FilteredDirectoryReader} the {@link FDRDefaultSimilarity}
 * will be used.//from w w w .  ja v a 2 s. co  m
 * @param reader Reader to use
 * @return Searcher instance
 */
public static IndexSearcher getSearcher(final IndexReader reader) {
    final IndexSearcher searcher = new IndexSearcher(reader);
    if (FilteredDirectoryReader.class.isInstance(reader) || FilteredLeafReader.class.isInstance(reader)) {
        searcher.setSimilarity(new FDRDefaultSimilarity());
    }
    return searcher;
}

From source file:Dl4j.TermInfo.java

public LuceneDocFetcher(Directory dir, ArrayList<String> docIds) throws Exception {

    globalTermId = 0;/*from w  w  w  . ja v a2  s  .c o m*/
    termSeen = new HashMap<>();

    IndexReader reader = DirectoryReader.open(dir);
    // totalExamples = reader.numDocs();
    //++Procheta
    totalExamples = docIds.size();
    docWordMaps = new ArrayList<>(totalExamples);

    // build the per-doc word maps
    for (int i = 0; i < totalExamples; i++) {

        IndexSearcher searcher = new IndexSearcher(reader);
        Similarity sm = new DefaultSimilarity();
        searcher.setSimilarity(sm);
        Analyzer analyzer = new KeywordAnalyzer();
        //System.out.println(id);
        QueryParser queryParser = new QueryParser("id", analyzer);
        Query query = queryParser.parse(docIds.get(i));
        TopDocs topDocs = searcher.search(query, 3);
        //System.out.println(query.toString());
        ScoreDoc[] hits = topDocs.scoreDocs;
        // System.out.println(hits.length);
        Document doc = searcher.doc(hits[0].doc);

        docWordMaps.add(buildTerms(reader, hits[0].doc));
    }

    // iterate through the word maps and build the one-hot vectors
    List<DataSet> allDocVecs = new ArrayList<>(totalExamples);
    for (Map<String, TermInfo> docwordMap : docWordMaps) {
        allDocVecs.add(constructTermVector(docwordMap));
    }

    // Merge all doc vecs into one dataset
    this.dataSet = DataSet.merge(allDocVecs);

    reader.close();
}

From source file:Dl4j.TermInfo.java

public LuceneDocFetcher(Directory dir, ArrayList<String> docIds, ArrayList<String> labels) throws Exception {

    globalTermId = 0;//  w  ww .j  a  va 2  s  .  com
    termSeen = new HashMap<>();

    IndexReader reader = DirectoryReader.open(dir);
    // totalExamples = reader.numDocs();
    //++Procheta
    totalExamples = docIds.size();
    docWordMaps = new ArrayList<>(totalExamples);

    // build the per-doc word maps
    for (int i = 0; i < totalExamples; i++) {

        IndexSearcher searcher = new IndexSearcher(reader);
        Similarity sm = new DefaultSimilarity();
        searcher.setSimilarity(sm);
        Analyzer analyzer = new KeywordAnalyzer();
        //System.out.println(id);
        QueryParser queryParser = new QueryParser("id", analyzer);
        Query query = queryParser.parse(docIds.get(i));
        TopDocs topDocs = searcher.search(query, 3);
        //System.out.println(query.toString());
        ScoreDoc[] hits = topDocs.scoreDocs;
        // System.out.println(hits.length);
        Document doc = searcher.doc(hits[0].doc);

        docWordMaps.add(buildTerms(reader, hits[0].doc));
    }

    // iterate through the word maps and build the one-hot vectors
    List<DataSet> allDocVecs = new ArrayList<>(totalExamples);
    for (Map<String, TermInfo> docwordMap : docWordMaps) {
        allDocVecs.add(constructTermVector(docwordMap, labels));
    }

    // Merge all doc vecs into one dataset
    this.dataSet = DataSet.merge(allDocVecs);

    reader.close();
}

From source file:edu.cmu.lti.oaqa.baseqa.document.rerank.LogRegDocumentReranker.java

License:Apache License

@Override
public void process(JCas jcas) throws AnalysisEngineProcessException {
    /*//from   w w  w  .j ava  2 s  .  com
    * ("arthritis"[MeSH Terms] OR "arthritis"[All Fields])
    *  AND common[All Fields] AND ("men"[MeSH Terms] OR "men"[All Fields])) OR ("women"[MeSH Terms] OR "women"[All Fields])
    */
    // calculate field scores
    List<Document> documents = TypeUtil.getRankedDocuments(jcas);
    Map<String, Document> id2doc = documents.stream().collect(toMap(Document::getDocId, Function.identity()));
    List<org.apache.lucene.document.Document> luceneDocs = documents.stream()
            .map(LogRegDocumentReranker::toLuceneDocument).collect(toList());
    RAMDirectory index = new RAMDirectory();
    try (IndexWriter writer = new IndexWriter(index, new IndexWriterConfig(analyzer))) {
        writer.addDocuments(luceneDocs);
    } catch (IOException e) {
        throw new AnalysisEngineProcessException(e);
    }
    AbstractQuery aquery = TypeUtil.getAbstractQueries(jcas).iterator().next();
    String queryString = queryStringConstructor.construct(aquery);
    LOG.info("Search for query: {}", queryString);
    Map<String, Float> id2titleScore = new HashMap<>();
    Map<String, Float> id2textScore = new HashMap<>();
    try (IndexReader reader = DirectoryReader.open(index)) {
        IndexSearcher searcher = new IndexSearcher(reader);
        searcher.setSimilarity(new BM25Similarity());
        Query titleQuery = parser.createBooleanQuery("title", queryString);
        ScoreDoc[] titleScoreDocs = searcher.search(titleQuery, hits).scoreDocs;
        LOG.info(" - Title matches: {}", titleScoreDocs.length);
        for (ScoreDoc titleScoreDoc : titleScoreDocs) {
            id2titleScore.put(searcher.doc(titleScoreDoc.doc).get("id"), titleScoreDoc.score);
        }
        Query textQuery = parser.createBooleanQuery("text", queryString);
        ScoreDoc[] textScoreDocs = searcher.search(textQuery, hits).scoreDocs;
        LOG.info(" - Text matches: {}", textScoreDocs.length);
        for (ScoreDoc textScoreDoc : textScoreDocs) {
            id2textScore.put(searcher.doc(textScoreDoc.doc).get("id"), textScoreDoc.score);
        }
    } catch (IOException e) {
        throw new AnalysisEngineProcessException(e);
    }
    // set score
    for (Map.Entry<String, Document> entry : id2doc.entrySet()) {
        String id = entry.getKey();
        Document doc = entry.getValue();
        doc.setScore(calculateScore(doc.getRank(), id2titleScore.getOrDefault(id, 0f),
                id2textScore.getOrDefault(id, 0f)));
    }
    TypeUtil.rankedSearchResultsByScore(documents, hits);
}

From source file:edu.cmu.lti.oaqa.baseqa.passage.retrieval.ImprovedLuceneInMemorySentenceRetrievalExecutor.java

License:Apache License

@Override
public void process(JCas jcas) throws AnalysisEngineProcessException {
    // create lucene documents for all sentences in all sections and delete the duplicate ones
    Map<Integer, Passage> hash2passage = new HashMap<Integer, Passage>();
    for (Passage d : TypeUtil.getRankedPassages(jcas)) {
        for (Passage s : RetrievalUtil.extractSentences(jcas, d, chunker)) {
            if (!hash2passage.containsKey(TypeUtil.hash(s))) {
                hash2passage.put(TypeUtil.hash(s), s);
            }/*from   w  ww .  ja  va  2s.c o  m*/
        }
    }
    // remove the documents from pipeline
    TypeUtil.getRankedPassages(jcas).forEach(Passage::removeFromIndexes);
    List<Document> luceneDocs = hash2passage.values().stream().map(RetrievalUtil::createLuceneDocument)
            .collect(toList());
    // create lucene index
    RAMDirectory index = new RAMDirectory();
    try (IndexWriter writer = new IndexWriter(index, new IndexWriterConfig(analyzer))) {
        writer.addDocuments(luceneDocs);
    } catch (IOException e) {
        throw new AnalysisEngineProcessException(e);
    }
    // search in the index
    AbstractQuery aquery = TypeUtil.getAbstractQueries(jcas).stream().findFirst().get();
    Map<Integer, Float> hash2score = new HashMap<>();
    try (IndexReader reader = DirectoryReader.open(index)) {
        IndexSearcher searcher = new IndexSearcher(reader);
        String queryString = queryStringConstructor.construct(aquery).replace("\"", " ").replace("/", " ")
                .replace("[", " ").replace("]", " ");
        LOG.info("Search for query: {}", queryString);

        // construct the query
        Query query = parser.parse(queryString);
        LOG.trace(query.toString());
        searcher.setSimilarity(new BM25Similarity());
        ScoreDoc[] scoreDocs = searcher.search(query, hits).scoreDocs;
        for (ScoreDoc scoreDoc : scoreDocs) {
            float score = scoreDoc.score;
            int hash;
            hash = Integer.parseInt(searcher.doc(scoreDoc.doc).get("hash"));
            hash2score.put(hash, score);
        }
    } catch (IOException | ParseException e) {
        throw new AnalysisEngineProcessException(e);
    }
    LOG.info("The size of Returned Sentences: {}", hash2score.size());
    // add to CAS
    hash2score.entrySet().stream().map(entry -> {
        Passage passage = hash2passage.get(entry.getKey());
        passage.setScore(entry.getValue());
        return passage;
    }).sorted(Comparator.comparing(Passage::getScore).reversed()).forEach(Passage::addToIndexes);

    Collection<Passage> snippets = TypeUtil.getRankedPassages(jcas);

    // rank the snippet and add them to pipeline
    rankSnippets(jcas, calSkip(jcas, hash2passage), calBM25(jcas, hash2passage),
            calAlignment(jcas, hash2passage), calSentenceLength(hash2passage), hash2passage);

}

From source file:edu.cmu.lti.oaqa.baseqa.passage.retrieval.ImprovedLuceneInMemorySentenceRetrievalExecutor.java

License:Apache License

private Map<Integer, Float> calBM25(JCas jcas, Map<Integer, Passage> hash2passage)
        throws AnalysisEngineProcessException {
    // index the documents using lucene
    List<Document> luceneDocs = hash2passage.values().stream().map(RetrievalUtil::createLuceneDocument)
            .collect(toList());//from  w  w  w.  j  av a2  s  .  c o m
    // create lucene index
    RAMDirectory index = new RAMDirectory();
    try (IndexWriter writer = new IndexWriter(index, new IndexWriterConfig(analyzer))) {
        writer.addDocuments(luceneDocs);
    } catch (IOException e) {
        throw new AnalysisEngineProcessException(e);
    }
    // search in the index
    AbstractQuery aquery = TypeUtil.getAbstractQueries(jcas).stream().findFirst().get();
    Map<Integer, Float> hash2score = new HashMap<>();
    try (IndexReader reader = DirectoryReader.open(index)) {
        IndexSearcher searcher = new IndexSearcher(reader);
        String queryString = queryStringConstructor.construct(aquery).replace("\"", " ").replace("/", " ")
                .replace("[", " ").replace("]", " ");
        LOG.info("Search for query: {}", queryString);

        // construct the query
        Query query = parser.parse(queryString);
        searcher.setSimilarity(new BM25Similarity());
        ScoreDoc[] scoreDocs = searcher.search(query, hits).scoreDocs;
        for (ScoreDoc scoreDoc : scoreDocs) {
            float score = scoreDoc.score;
            int hash;
            hash = Integer.parseInt(searcher.doc(scoreDoc.doc).get("hash"));
            hash2score.put(hash, score);
        }
    } catch (IOException | ParseException e) {
        throw new AnalysisEngineProcessException(e);
    }
    return hash2score;
}

From source file:edu.ucla.sspace.lra.LatentRelationalAnalysis.java

License:Open Source License

private static float searchPhrase(File indexDir, String A, String B) throws Exception {
    Directory fsDir = FSDirectory.getDirectory(indexDir);
    IndexSearcher searcher = new IndexSearcher(fsDir);

    long start = new Date().getTime();
    QueryParser parser = new QueryParser("contents", new StandardAnalyzer());
    //System.err.println("searching for: '\"" + A + " " + B + "\"~"+MAX_PHRASE+"'");
    parser.setPhraseSlop(MAX_PHRASE);/*from ww  w .j a v  a2s .  c o  m*/
    String my_phrase = "\"" + A + " " + B + "\"";
    Query query = parser.parse(my_phrase);
    //System.err.println("total hits: " + results.totalHits);

    //set similarity to use only the frequencies
    //score is based on frequency of phrase only
    searcher.setSimilarity(new Similarity() {
        public static final long serialVersionUID = 1L;

        public float coord(int overlap, int maxOverlap) {
            return 1;
        }

        public float queryNorm(float sumOfSquaredWeights) {
            return 1;
        }

        public float tf(float freq) {
            return freq;
        }

        public float idf(int docFreq, int numDocs) {
            return 1;
        }

        public float lengthNorm(String fieldName, int numTokens) {
            return 1;
        }

        public float sloppyFreq(int distance) {
            return 1;
        }
    });
    TopDocs results = searcher.search(query, 10);

    ScoreDoc[] hits = results.scoreDocs;
    float total_score = 0;
    //add up the scores
    for (ScoreDoc hit : hits) {
        Document doc = searcher.doc(hit.doc);
        //System.err.printf("%5.3f %sn\n",
        //   hit.score, doc.get("contents"));
        total_score += hit.score;
    }

    long end = new Date().getTime();
    searcher.close();

    return total_score;
}

From source file:es.pode.indexador.negocio.servicios.busqueda.SrvBuscadorServiceImpl.java

License:Open Source License

/**
 * @see es.pode.indexador.negocio.servicios.busqueda.SrvBuscadorService#busquedaLOM_ES(es.pode.indexador.negocio.servicios.busqueda.ParamAvanzadoVO)
 * @param QuerySimpleVO Parametros de una query simple.
 * @return DocumentosLOM_ESVO Esta clase representa los documentos resultado de una busqueda por LOM_ES.
 *//*from  w w w .ja  va2s.c om*/
protected es.pode.indexador.negocio.servicios.busqueda.DocumentosLOM_ESVO handleBusquedaLOM_ES(
        es.pode.indexador.negocio.servicios.busqueda.QuerySimpleVO paramBusq) throws java.lang.Exception {
    DocumentosLOM_ESVO respuesta = new DocumentosLOM_ESVO();
    DocLOM_ESVO[] resultados = null;
    DisjunctionMaxQuery query = new DisjunctionMaxQuery(0.01f);
    String queryLang = paramBusq.getLenguajeQuery();
    String idioma = paramBusq.getIdioma();
    String unparsedQuery = paramBusq.getQuery();
    Hits hits = null;
    logger.debug(
            "Se ha recibido una query en lenguaje[" + queryLang + "] con contenido[" + unparsedQuery + "]");
    // Discriminar SQI / Lucene
    if (SQI_LANG.equals(queryLang)) {
        logger.debug("Parseando query SQI_LANG[" + unparsedQuery + "]");
        String[] terms = parsearVSQL(unparsedQuery);
        // Introduzco los terminos de busqueda en titulo, descripcion y
        // palabras clave
        logger.debug("Creando query a partir de terminos[" + terms + "]");
        for (int i = 0; i < terms.length; i++) {
            query.add(getTermQuery(props.getProperty("campo_titulo"), terms[i].toLowerCase()));
            query.add(getTermQuery(props.getProperty("campo_descripcion"), terms[i].toLowerCase()));
            query.add(getTermQuery(props.getProperty("campo_palabrasClave"), terms[i].toLowerCase()));
        }
        if (logger.isDebugEnabled())
            logger.debug("Consulta LOM_ES con query[" + query.toString() + "] a partir de SQUI lenguaje.");
    } else if (LUCENE_LANG.equals(queryLang)) {
        logger.debug("Parseando query LUCENE_LANG" + unparsedQuery);
        QueryParser parser = new QueryParser(props.getProperty("campo_titulo"), new StandardAnalyzer());
        parser.setLowercaseExpandedTerms(true);
        Query lqsQuery = parser.parse(unparsedQuery);
        query.add(lqsQuery);
        if (logger.isDebugEnabled())
            logger.debug("Consulta LOM_ES con query[" + query.toString() + "] a partir de LUCENE lenguaje.");
    } else {
        logger.error("Se ha recibido una query que no es SQI ni Lucene =>[" + queryLang + "].");
        throw new Exception("Se ha recibido una query que no es SQI ni Lucene =>[" + queryLang + "].");
    }

    // Preparando busqueda
    logger.debug("Preparando busqueda");
    Directory directorioIndiceSimple = this.getIndexByLanguage(idioma);
    logger.debug("Directory directorioIndiceSimple[" + directorioIndiceSimple + "]");
    IndexSearcher searcher = new IndexSearcher(directorioIndiceSimple);
    searcher.setSimilarity(new DefaultSimilarity());
    if (logger.isDebugEnabled())
        logger.debug("Consulta LOM_ES con query[" + query.toString() + "]");
    hits = searcher.search(query);
    logger.debug("Numero de hits obtenidos[" + (hits != null ? hits.length() : 0) + "]");
    if (hits != null && hits.length() > 0) {
        logger.debug("Numero de hits[" + hits.length() + "]");

        resultados = new DocLOM_ESVO[hits.length()];

        logger.debug("resultados[" + resultados + "]");

        for (int i = 0; i < hits.length(); i++) {
            DocLOM_ESVO hitToDoc = new DocLOM_ESVO();
            Document doc = hits.doc(i);
            logger.debug("Document doc : " + doc);
            String localizador = doc.get(props.getProperty("campo_localizador"));

            logger.debug("localizador : " + localizador);
            hitToDoc.setRanking(new Integer(Float.floatToIntBits(hits.score(i))));

            Manifest manifest = this.parsearManifiesto(localizador + File.separator + "imsmanifest.xml");
            Lom lom = null;

            if (manifest != null) {
                logger.debug("manifest!=null " + manifest);

                ManifestAgrega ma = new ManifestAgrega(manifest);
                lom = ma.obtenerLom(manifest.getIdentifier(), null);

                /*
                 * Este codigo seguramente es viejo: El mapeo de Lom a Lom
                 * entiendo que es innecesario: para escribir el lomes a un
                 * Write no es necesario tener un clon del objeto Lom.
                 * 
                 * La forma recomendada de obtener el Lom de un Manifest es
                 * mediante los metodos de la clase ManifestAgrega
                 * 
                 * fjespino
                 */
                //               lom = this.getLom(manifest.getMetadata(), manifest.getIdentifier());
                //               lomCastor = (es.pode.parseadorXML.lomes.Lom) beanMapper
                //                     .map(lom, es.pode.parseadorXML.lomes.Lom.class);

                //               creo un writer para escribir los metadatos
                StringWriter sw = new StringWriter();
                //completo el writer
                this.getLomesDao().escribirLom(lom, sw);
                hitToDoc.setDocumento(sw.toString());
                resultados[i] = hitToDoc;
            }
            logger.debug("manifest==null " + manifest);
        }
        respuesta.setResultados(resultados);
    }
    return respuesta;
}

From source file:es.pode.indexador.negocio.servicios.busqueda.SrvBuscadorServiceImpl.java

License:Open Source License

/**
 * @see es.pode.indexador.negocio.servicios.busqueda.SrvBuscadorServiceBase#handleSolicitudDocsCountArbolCurricular(ParamDocsCountVO)
 * //  ww w. ja v  a 2  s . c  om
 * @param ParamDocsCountVO VO que alberga los parametros que acepta una solicitud de numero de documentos para el nodo de un arbol curricular.
 * @return ResultadosCountVO VO que alberga el resultado de la solicitud de la suma de documentos para un nodo de arbol curricular.
 */
protected ResultadosCountVO handleSolicitudDocsCount(ParamDocsCountVO paramBusq) throws Exception {
    //      logger.debug("SrvBuscadorServiceImpl - handleSolicitudDocsCount: AreaCurricular=" + array2String(paramBusq.getAreaCurricular())+ ", Tesauros="+array2String(paramBusq.getTesauros()));
    //      return NumTermsArbol.obtenerNumeroNodos(paramBusq.getAreaCurricular(),getIndexPathByLanguage(paramBusq.getIdiomaBusqueda()),(paramBusq.getAreaCurricular()!=null && paramBusq.getAreaCurricular().length > 0)?"areaCurricular":"tesauro");
    Directory directorioIndiceSimple = this.getIndexByLanguage(paramBusq.getIdiomaBusqueda());
    IndexSearcher searcher = new IndexSearcher(directorioIndiceSimple);
    ResultadosCountVO resultado = new ResultadosCountVO();
    searcher.setSimilarity(new DefaultSimilarity());
    int suma = 0;
    if (paramBusq.getAreaCurricular() != null && paramBusq.getAreaCurricular().length > 0) {
        resultado.setConteo(new Integer[paramBusq.getAreaCurricular().length]);
        for (int i = 0; i < paramBusq.getAreaCurricular().length; i++) {
            BooleanQuery andQuery = new BooleanQuery();
            andQuery.add(
                    getTermQuery(props.getProperty(CAMPO_AREA_CURRICULAR), paramBusq.getAreaCurricular()[i]),
                    BooleanClause.Occur.MUST);
            andQuery.add(getTermQuery(props.getProperty(CAMPO_ARBOL_CURRICULAR_VIGENTE),
                    paramBusq.getArbolCurricularVigente()), BooleanClause.Occur.MUST);
            Hits hits = searcher.search(andQuery);
            resultado.getConteo()[i] = new Integer(hits.length());
            suma = suma + resultado.getConteo()[i].intValue();
        }
        resultado.setDocumentosCount(new Integer(suma));
    } else {
        resultado = NumTermsArbol.obtenerNumeroNodos(paramBusq.getTesauros(),
                getIndexPathByLanguage(paramBusq.getIdiomaBusqueda()), "tesauro");
    }
    return resultado;
}

From source file:es.pode.indexador.negocio.servicios.busqueda.SrvBuscadorServiceImpl.java

License:Open Source License

/**
 * Este metodo busca los documentos indexados que cumplen estar dentro del rango de fechas dado y que tengan el valor de licencia dado.
 * /*  w ww .j  a v  a2  s . co  m*/
 * @param licencia Licencia de la que se quiere saber el numero de documentos que la contiene.
 * @param fechaDesde Fecha desde del periodo en el que se esta interesado.
 * @param fechaHasta Fecha hasta del periodo en el que se esta interesado.
 * @param idioma Idioma en el que se esta interesado buscar.
 * @return ResultadosCountVO VO que alberga el resultado de la solicitud de la suma de documentos que cumplen la condicion.
 */
protected ResultadosCountVO handleBusquedaDocsLicenciaFecha(String licencia, Calendar fechaDesde,
        Calendar fechaHasta, String idioma) throws Exception {
    if (licencia == null || licencia.equals("")) {
        logger.error("Error buscando documentos con licencias. Licencia vacia.");
        throw new Exception("Error buscando documentos con licencias. Licencia vacia.");
    }
    if (idioma == null || idioma.equals("")) {
        logger.error("Error buscando documentos con licencias. Idioma de busqueda vacio.");
        throw new Exception("Error buscando documentos con licencias. Idioma de busqueda vacio.");
    }
    if (fechaDesde == null || fechaHasta == null) {
        logger.error("Error buscando documentos con licencias. Fechas desde[" + fechaDesde == null ? null
                : fechaDesde.toString() + "] y hasta[" + fechaHasta == null ? null
                        : fechaHasta.toString() + "] vacias.");
        throw new Exception("Error buscando documentos con licencias. Fechas desde[" + fechaDesde == null ? null
                : fechaDesde.toString() + "] y hasta[" + fechaHasta == null ? null
                        : fechaHasta.toString() + "] vacias.");
    }
    if (fechaDesde.after(fechaHasta)) {
        logger.error("Error buscando documentos con licencias. Fechas desde[" + fechaDesde.toString()
                + "] y hasta[" + fechaHasta.toString() + "] incoherentes.");
        throw new Exception("Error buscando documentos con licencias. Fechas desde[" + fechaDesde.toString()
                + "] y hasta[" + fechaHasta.toString() + "] incoherentes.");
    }
    BooleanQuery andQuery = new BooleanQuery();
    //      Configuramos el valor de memoria.   
    andQuery.setMaxClauseCount(Integer.parseInt(props.getProperty("maxClauseCount")));
    Calendar antes = Calendar.getInstance();
    Calendar despues = Calendar.getInstance();
    antes.setTime(fechaDesde.getTime());
    despues.setTime(fechaHasta.getTime());
    String antesS = "" + antes.get(Calendar.YEAR) + formatMonthMM((antes.get(Calendar.MONTH) + 1))
            + formatDayDD(antes.get(Calendar.DAY_OF_MONTH));
    String despuesS = "" + despues.get(Calendar.YEAR) + formatMonthMM((despues.get(Calendar.MONTH) + 1))
            + formatDayDD(despues.get(Calendar.DAY_OF_MONTH));
    logger.debug(
            "Buscando documentos con licencia[" + licencia + "] desde[" + antesS + "] hasta[" + despuesS + "]");
    //aniadimos la query con el rango de fechas
    andQuery.add(getRangeQuery(props.getProperty(CAMPO_FECHA_PUBLICACION), antesS, despuesS),
            BooleanClause.Occur.MUST);
    //aniadimos la query con el id de la licencia
    //       QueryParser parser = new QueryParser(props.getProperty(CAMPO_LICENCIA), new StandardAnalyzer());
    //          // el standar analyzer utiliza el StandardTokenizer gracias al cual elimina de la licencia los caracteres extranios
    //          // para ver que caracteres tiene en cuenta al tokenizar:http://lucene.zones.apache.org:8080/hudson/job/Lucene-Nightly/javadoc/org/apache/lucene/analysis/standard/StandardTokenizer.html
    //      Query licenciaQuery = parser.parse("\""+licencia+"\""); //tenemos en cuenta el texto entre comillas para que el parseo no se pierda.
    //         // hemos convertido en tokens las palabras de la licencia
    //       andQuery.add(getPhraseQuery(props.getProperty(CAMPO_LICENCIA), Arrays.asList(licencia.split(" "))),BooleanClause.Occur.MUST);
    andQuery.add(getTermQuery(props.getProperty(CAMPO_LICENCIA), licencia), BooleanClause.Occur.MUST);
    //      andQuery.add(licenciaQuery,BooleanClause.Occur.MUST);

    //      Utilizamos el idioma seleccionado en la busqueda para buscar el indice sobre el que se ejecuta la query.
    Directory directorioIndiceSimple = this.getIndexByLanguage(idioma);
    if (directorioIndiceSimple == null) {
        logger.error("Error buscando documentos con licencias. Indice para idioma[" + idioma
                + "] no accesible. Imposible buscar.");
        throw new Exception("Error buscando documentos con licencias. Indice para idioma[" + idioma
                + "] no accesible. Imposible buscar.");
    }
    Hits hits;
    try {
        IndexSearcher searcher = new IndexSearcher(directorioIndiceSimple);
        searcher.setSimilarity(new DefaultSimilarity());
        hits = searcher.search(andQuery);
    } catch (Exception e) {
        logger.error("Error buscando documentos con licencias. Error buscando en indice[" + idioma
                + "] con query[" + andQuery.toString() + "].[" + e.getCause() + "]");
        throw new Exception("Error buscando documentos con licencias. Error buscando en indice[" + idioma
                + "] con query[" + andQuery.toString() + "].", e);
    }
    ResultadosCountVO resultado = new ResultadosCountVO();
    if (hits != null)
        resultado.setDocumentosCount(new Integer(hits.length()));
    else
        resultado.setDocumentosCount(new Integer(0));
    return resultado;
}