Example usage for org.apache.lucene.search BooleanQuery setMaxClauseCount

List of usage examples for org.apache.lucene.search BooleanQuery setMaxClauseCount

Introduction

In this page you can find the example usage for org.apache.lucene.search BooleanQuery setMaxClauseCount.

Prototype

public static void setMaxClauseCount(int maxClauseCount) 

Source Link

Document

Set the maximum number of clauses permitted per BooleanQuery.

Usage

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

License:Open Source License

/**
* Este metodo devuelve todos los ODEs indexados en el repositorio para todos los idiomas.
* @return ResultadoRepositorioVO[] Array de VO's que albergan los resulados del repositorio.
*//*w ww  . ja v a 2  s  .  c  o m*/
protected ResultadoRepositorioVO[] handleObtenerRepositorio() throws Exception {

    Date fechaDesde = handleFechaInicioRepositorio().getTime();
    Date fechaHasta = Calendar.getInstance().getTime(); // la fecha de hoy como hasta

    //      Obtenemos todos los indices sobre los que hay objetos
    IndiceVO[] indices = new IndiceVO[0];
    try {
        indices = handleObtenerIdiomasBusqueda();
    } catch (Exception e) {
        logger.error("Error recuperando repositorio. Imposible recuperar los indices.[" + e.getMessage() + "]");
        throw new Exception("Error recuperando repositorio. Imposible recuperar los indices.", e);
    }
    //     Para cada indice, tenemos que recoger todos los odes.
    if (indices == null || indices.length == 0) {
        logger.error("Error recuperando repositorio. No existen indices en el indexador. Imposible continuar.");
        throw new Exception(
                "Error recuperando repositorio. No existen indices en el indexador. Imposible continuar.");
    }

    //       Configuramos la query que se va a realizar sobre el indice
    BooleanQuery andQuery = new BooleanQuery();
    //      Configuramos el valor de memoria.   
    andQuery.setMaxClauseCount(Integer.parseInt(props.getProperty("maxClauseCount")));
    //       Configuramos la fecha desde
    String antesS = null;
    String despuesS = null;
    if (fechaDesde != null) {
        Calendar antes = Calendar.getInstance();
        antes.setTime(fechaDesde);
        antesS = "" + antes.get(Calendar.YEAR) + formatMonthMM((antes.get(Calendar.MONTH) + 1))
                + formatDayDD(antes.get(Calendar.DAY_OF_MONTH));
    }
    //       Configuramos la fecha hasta
    if (fechaHasta != null) {
        Calendar despues = Calendar.getInstance();
        despues.setTime(fechaHasta);
        despuesS = "" + despues.get(Calendar.YEAR) + formatMonthMM((despues.get(Calendar.MONTH) + 1))
                + formatDayDD(despues.get(Calendar.DAY_OF_MONTH));
    }
    logger.debug("Recuperando repositorio desde[" + antesS + "] hasta[" + despuesS + "]");
    //aniadimos la query con el rango de fechas
    andQuery.add(getConstantScoreRangeQuery(props.getProperty(CAMPO_FECHA_PUBLICACION), antesS, despuesS),
            BooleanClause.Occur.MUST);

    //      Nos recorremos todos los indices realizando la misma consulta y recopilando la informacion que saquemos de cada indice
    ArrayList resultados = new ArrayList();
    for (int i = 0; i < indices.length; i++) {
        Directory directorioIndiceSimple = this.getIndexByLanguage(indices[i].getIdentificador());
        if (directorioIndiceSimple == null) {
            logger.error("Error recuperando repositorio. Indice para idioma[" + indices[i].getIdentificador()
                    + "] no accesible. Imposible buscar.");
            throw new Exception("Error recuperando repositorio. Indice para idioma["
                    + indices[i].getIdentificador() + "] no accesible. Imposible buscar.");
        }
        Hits hits = null;
        try {
            IndexSearcher searcher = new IndexSearcher(directorioIndiceSimple);
            searcher.setSimilarity(new DefaultSimilarity());
            hits = searcher.search(andQuery);
            //             Dejamos de aplicar el filtro de licencia. Nos interesan todos los ODEs del repositorio
            //             hits = searcher.search(andQuery, crearFiltroLicencia());
        } catch (Exception e) {
            logger.error(
                    "Error recuperando repositorio. Error buscando en indice[" + indices[i].getIdentificador()
                            + "] con query[" + andQuery.toString() + "].[" + e.getCause() + "]");
            //             En el caso de que el indice de error, miro por el resto.
            //             throw new Exception("Error recuperando repositorio. Error buscando en indice["+indices[i].getIdentificador()+"] con query["+andQuery.toString()+"].",e);
        }
        if (hits != null && hits.length() > 0) {
            logger.info("Recuperando repositorio. Informacion de repositorio disponible para idioma["
                    + indices[i].getIdentificador() + "] fechas[" + antesS + "-" + despuesS + "] query["
                    + andQuery.toString() + "] documentos[" + hits.length() + "]");
            try {
                resultados.addAll(Arrays.asList(mapDocToRepositorio(hits)));
            } catch (RuntimeException e) {
                logger.error("Error recuperando repositorio. Error mapeando resultados para indice["
                        + indices[i].getIdentificador() + "] con query[" + andQuery.toString() + "].["
                        + e.getCause() + "]");
                throw new Exception(
                        "Error recuperando repositorio. Error mapeando resultados para indice["
                                + indices[i].getIdentificador() + "] con query[" + andQuery.toString() + "].",
                        e);
            }
        } else {
            logger.info("Recuperando repositorio. No hay informacion de repositorio disponible para idioma["
                    + indices[i].getIdentificador() + "] fechas[" + antesS + "-" + despuesS + "] query["
                    + andQuery.toString() + "]");
        }
    }
    return (ResultadoRepositorioVO[]) resultados.toArray(new ResultadoRepositorioVO[resultados.size()]);
}

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

License:Open Source License

private Hits internaBusquedaAvanzada(es.pode.indexador.negocio.servicios.busqueda.ParamAvanzadoVO paramBusq,
        DisjunctionMaxQuery query) throws Exception {
    Directory directorioIndiceSimple = null;
    IndexSearcher searcher = null;/* w w  w .ja  v  a  2  s.c o  m*/
    Hits hits = null;
    //      Utilizamos el idioma seleccionado en la busqueda para buscar el indice sobre el que se ejecuta la query.
    try {
        //      Utilizamos el idioma seleccionado en la busqueda para buscar el indice sobre el que se ejecuta la query.
        directorioIndiceSimple = this.getIndexByLanguage(paramBusq.getIdiomaBusqueda());
        searcher = new IndexSearcher(directorioIndiceSimple);
        BooleanQuery andQuery = new BooleanQuery();
        //      Las palabras clave (texto libre que se pone en la cabecera de la pantalla de busqueda) sirve para buscar
        //      sobre los campos titulo, descripcion y keywords
        //      Configuramos el valor de memoria.      
        andQuery.setMaxClauseCount(Integer.parseInt(props.getProperty("maxClauseCount")));
        //      Separamos las posibles frases de las palabras sueltas
        if (paramBusq.getPalabrasClave() != null && !paramBusq.getPalabrasClave().trim().equals("")) {
            List palabras = devolverFrases(paramBusq.getPalabrasClave().trim(), paramBusq.getIdiomaBusqueda());
            List ands = devolverAnds(palabras);
            String[] claves = props.getProperty(CAMPOS_CLAVE_AVANZADA).split(SEPARADOR_CLAVES);
            if (ands != null) {
                BooleanQuery andQueryClavePrincipal = new BooleanQuery();
                andQueryClavePrincipal.setMaxClauseCount(Integer.parseInt(props.getProperty("maxClauseCount")));
                List andsList = (List) ands.get(0);
                List orList = (List) ands.get(1);

                // Two lists ... one with words with a + before andList
                //               second one with rest of tokens (common words)   orList
                BooleanQuery andQueryClave = new BooleanQuery();
                andQueryClave.setMaxClauseCount(Integer.parseInt(props.getProperty("maxClauseCount")));
                for (int k = 0; k < claves.length; k++) {
                    for (int j = 0; j < andsList.size(); j++) {
                        BooleanQuery andQueryClaveInterna = new BooleanQuery();
                        andQueryClaveInterna
                                .setMaxClauseCount(Integer.parseInt(props.getProperty("maxClauseCount")));
                        for (int i = 0; i < ((List) andsList.get(j)).size(); i++) {
                            andQueryClaveInterna.add((List.class.isInstance(((List) andsList.get(j)).get(i)))
                                    ? getQuery(((List) andsList.get(j)).get(i), claves[k],
                                            CAMPOS_PHRASE_AVANZADA)
                                    : getQuery(((List) andsList.get(j)).get(i).toString(), claves[k],
                                            CAMPOS_WILDCARD_AVANZADA),
                                    BooleanClause.Occur.MUST);
                        }
                        andQueryClave.add(andQueryClaveInterna, BooleanClause.Occur.MUST);
                    }
                } //until here it treats words in the query with + before
                  // and now is the treatment for orList
                for (int j = 0; j < orList.size(); j++) {
                    BooleanQuery andQueryClaveInterna = new BooleanQuery();
                    andQueryClaveInterna
                            .setMaxClauseCount(Integer.parseInt(props.getProperty("maxClauseCount")));
                    for (int k = 0; k < claves.length; k++) {
                        //andQueryClaveInterna.add((List.class.isInstance(orList.get(j)))?getQuery(orList.get(j),claves[k],CAMPOS_PHRASE_AVANZADA):getQuery(orList.get(j).toString(),claves[k],CAMPOS_WILDCARD_AVANZADA),BooleanClause.Occur.SHOULD);

                        Query q1 = null;
                        if (List.class.isInstance(orList.get(j))) {
                            logger.debug(
                                    "* CAMPOS_PHRASE_AVANZADA   j=" + j + "  orList.get(j))=" + orList.get(j));
                            q1 = getQuery(orList.get(j), claves[k], CAMPOS_PHRASE_AVANZADA);
                        } else {
                            logger.debug(
                                    "* CAMPOS_WILDCARD_AVANZADA j=" + j + "  orList.get(j))=" + orList.get(j));
                            q1 = getQuery(orList.get(j).toString(), claves[k], CAMPOS_WILDCARD_AVANZADA);
                        }

                        andQueryClaveInterna.add(q1, BooleanClause.Occur.SHOULD);

                    }
                    andQueryClave.add(andQueryClaveInterna, BooleanClause.Occur.MUST);//original MUST
                }
                // Add the filter TermQueries as clauses
                addFiltersToQuery(paramBusq.getSearchFilters(), andQueryClave);

                andQuery.add(andQueryClave, BooleanClause.Occur.MUST);
                query.add(andQuery);
            }
        }
        //      Ahora recorremos todos los parametros de la busqueda avanzada, introduciendo los valores de busqueda
        //      en la query de aquellos campos que esten presentes en los parametros de la consulta.
        PropertyDescriptor[] beanPDs = Introspector.getBeanInfo(paramBusq.getClass()).getPropertyDescriptors();
        for (int j = 0; j < beanPDs.length; j++) {
            if (props.getProperty(PREFIJO_CAMPO + beanPDs[j].getName()) != null
                    && (getAndOrAccess(beanPDs[j].getName(), true)
                            || getAndOrAccess(beanPDs[j].getName(), false))) {
                if (beanPDs[j].getReadMethod().invoke(paramBusq, new Object[0]) != null && !beanPDs[j]
                        .getReadMethod().invoke(paramBusq, new Object[0]).toString().trim().equals("")) {
                    //               Comprobar analyse para no tener un tratamiento especial para formato

                    List palabras = new ArrayList();
                    if (getRangeQueryAccess(props.getProperty(CAMPOS_RANGE_AVANZADA).split(SEPARADOR_CLAVES),
                            PREFIJO_CAMPO + beanPDs[j].getName())
                            || esTextoLibre(props.getProperty(CAMPOS_TEXTO_LIBRE).split(SEPARADOR_CLAVES),
                                    PREFIJO_CAMPO + beanPDs[j].getName()))
                        palabras = devolverFrases(
                                beanPDs[j].getReadMethod().invoke(paramBusq, new Object[0]).toString().trim(),
                                paramBusq.getIdiomaBusqueda());
                    else
                        palabras.add(
                                beanPDs[j].getReadMethod().invoke(paramBusq, new Object[0]).toString().trim());
                    if (getRangeQueryAccess(props.getProperty(CAMPOS_RANGE_AVANZADA).split(SEPARADOR_CLAVES),
                            PREFIJO_CAMPO + beanPDs[j].getName()))
                        andQuery.add(
                                getRangeQuery(props.getProperty(PREFIJO_CAMPO + beanPDs[j].getName()),
                                        palabras.get(0).toString(), palabras.get(1).toString()),
                                BooleanClause.Occur.MUST);
                    else {
                        List ands = devolverAnds(palabras);
                        List andsList = (List) ands.get(0);
                        List orList = (List) ands.get(1);
                        BooleanQuery andQueryClave = new BooleanQuery();
                        andQueryClave.setMaxClauseCount(Integer.parseInt(props.getProperty("maxClauseCount")));
                        for (int k = 0; k < andsList.size(); k++) {
                            BooleanQuery andQueryClaveInterna = new BooleanQuery();
                            andQueryClaveInterna
                                    .setMaxClauseCount(Integer.parseInt(props.getProperty("maxClauseCount")));
                            for (int i = 0; i < ((List) andsList.get(k)).size(); i++) {
                                andQueryClaveInterna
                                        .add((List.class.isInstance(((List) andsList.get(k)).get(i)))
                                                ? getQuery(((List) andsList.get(k)).get(i),
                                                        PREFIJO_CAMPO + beanPDs[j].getName(),
                                                        CAMPOS_PHRASE_AVANZADA)
                                                : getQuery(((List) andsList.get(k)).get(i).toString(),
                                                        PREFIJO_CAMPO + beanPDs[j].getName(),
                                                        CAMPOS_WILDCARD_AVANZADA),
                                                BooleanClause.Occur.MUST);
                            }
                            andQueryClave.add(andQueryClaveInterna, BooleanClause.Occur.SHOULD);
                        }
                        for (int k = 0; k < orList.size(); k++) {
                            andQueryClave.add((List.class.isInstance(orList.get(k)))
                                    ? getQuery(orList.get(k), PREFIJO_CAMPO + beanPDs[j].getName(),
                                            CAMPOS_PHRASE_AVANZADA)
                                    : getQuery(orList.get(k).toString(), PREFIJO_CAMPO + beanPDs[j].getName(),
                                            CAMPOS_WILDCARD_AVANZADA),
                                    BooleanClause.Occur.SHOULD);
                        }
                        if (getAndOrAccess(beanPDs[j].getName(), true))
                            andQuery.add(andQueryClave, BooleanClause.Occur.MUST);
                        else if (getAndOrAccess(beanPDs[j].getName(), false))
                            andQuery.add(andQueryClave, BooleanClause.Occur.SHOULD);
                    }
                }
            }
        }
        if (logger.isDebugEnabled())
            logger.debug("Consulta interna simple con query[" + query.toString() + "]");

        Sort sortMethod = chooseSorter(paramBusq);
        logger.debug("About to do the search. It will be sorted with :" + sortMethod.toString());
        hits = searcher.search(andQuery, sortMethod);

        Iterator it = hits.iterator();
        int i = 1;
        logger.debug("* Lucene results");
        while (it.hasNext()) {
            org.apache.lucene.search.Hit hit = (org.apache.lucene.search.Hit) it.next();
            logger.debug("* FechaPublicacion=" + hit.get("fechaPublicacion") + " Id=" + hit.getId() + " S="
                    + hit.getScore() + "->" + hit.get("title"));
            i++;
        }
        logger.debug("* " + (i != 0 ? i - 1 : i) + " results");

        //(paramBusq.getBusquedaSimpleAvanzada()!=null && paramBusq.getBusquedaSimpleAvanzada().equals(BUSCARRSS))?new Sort(new SortField(props.getProperty("campo_fechaPublicacion"),SortField.STRING,true)):new Sort(new SortField(props.getProperty("campo_nivelAgregacion"),SortField.STRING,true)));
    } catch (java.lang.Exception e) {
        logger.error("Search failed", e);
        if (directorioIndiceSimple == null || searcher == null)
            logger.error(
                    "SrvBuscarServiceImpl - internaBusquedaAvanzada ERROR: No existe  ndice para el idioma = "
                            + paramBusq.getIdiomaBusqueda());
        else {
            Exception exc = new Exception("SrvBuscarServiceImpl - internaBusquedaAvanzada ERROR: Con query="
                    + paramBusq.getPalabrasClave() + " e idioma=" + paramBusq.getIdiomaBusqueda(), e);
            logger.error(exc);
            throw exc;
        }
    }
    return hits;
}

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

License:Open Source License

private void addFiltersToQuery(java.util.HashMap filters, BooleanQuery q) throws IOException {

    // Search filters are "nillable" in the WS contract
    if (filters == null)
        return;//w  w  w .j a va 2 s.  c o m

    // Add filter terms corresponding to each key in the map
    for (Object k : filters.keySet()) {
        if (k instanceof String) {

            if (k.equals("campo_formato")) {

                BooleanQuery queryFormato = new BooleanQuery();
                queryFormato.setMaxClauseCount(Integer.parseInt(props.getProperty("maxClauseCount")));

                Analyzer analyser = new StandardAnalyzer();
                /// We could change here the analyzer
                //Analyzer analyser = new WhitespaceAnalyzer();

                TokenStream stream = analyser.tokenStream((String) k,
                        new StringReader(filters.get(k).toString()));

                while (true) {
                    Token tok = stream.next();
                    if (tok == null)
                        break; // No more tokens for this filter field

                    queryFormato.add(new TermQuery(new Term(props.getProperty((String) k), tok.termText())),
                            BooleanClause.Occur.SHOULD);
                }

                q.add(queryFormato, BooleanClause.Occur.MUST);

            } else {

                // Each of these filtering fields is tokenised because it is
                // made available for arbitrary search with "contains" behavior.
                //
                // Use the default analyser to tokenise the search filter field
                // values before adding them as query sub-clauses.
                //
                // Note that if you ever need to add a filter corresponding to
                // an non-analysed field DO NOT tokenise it.

                Analyzer analyser = new StandardAnalyzer();
                /// We could change here the analyzer
                //Analyzer analyser = new WhitespaceAnalyzer();

                // Invoke toString() instead of checking and casting.
                // This would allow other Object types as values.

                TokenStream stream = analyser.tokenStream((String) k,
                        new StringReader(filters.get(k).toString()));

                // Unfortunately, stream does not support an iterator interface
                // so we will need to break out of an unbounded loop when done.

                while (true) {
                    Token tok = stream.next();
                    if (tok == null)
                        break; // No more tokens for this filter field

                    // A key represents a name for an indexed field; the value
                    // for which is in the properties configuration.

                    q.add(new TermQuery(new Term(props.getProperty((String) k), tok.termText())),
                            BooleanClause.Occur.MUST);
                }
            } //k.equals("campo_formato")
        }

    }
}

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

License:Open Source License

/**
 * @see es.pode.indexador.negocio.servicios.busqueda.SrvBuscadorService#handleObtenerCatalogoRepositorio()
 * @param nivelAgregacion Nivel de agregacion minimo que tienen que cumplir los ODEs del catalogo que se genere.
 * @return ResultadoRepositorioVO[] Fecha Devuelve un array de objetos de valor con informaci n indexada de los ODEs.
 *//*  ww  w .  jav a  2  s .  c o m*/
protected ResultadoRepositorioVO[] handleObtenerCatalogoRepositorioParam(Integer nivelAgregacion)
        throws Exception {

    String nivelAgregacionStr = "";
    if (nivelAgregacion == null) {
        logger.error("Error recuperando repositorio nivel agregacion[" + nivelAgregacion
                + "]. Nivel de agregacion nulo.");
        throw new Exception("Error recuperando repositorio nivel agregacion[" + nivelAgregacion
                + "]. Nivel de agregacion nulo.");
    } else {
        try {
            nivelAgregacionStr = Integer.toString(nivelAgregacion);
        } catch (Exception e) {
            logger.error("Error recuperando repositorio nivel agregacion[" + nivelAgregacion
                    + "]. Nivel de agregacion invalido.");
            throw new Exception("Error recuperando repositorio nivel agregacion[" + nivelAgregacion
                    + "]. Nivel de agregacion invalido.", e);
        }
    }
    //         Obtenemos todos los indices sobre los que hay objetos
    IndiceVO[] indices = new IndiceVO[0];
    try {
        indices = handleObtenerIdiomasBusqueda();
    } catch (Exception e) {
        logger.error("Error recuperando repositorio nivel agregacion[" + nivelAgregacion
                + "]. Imposible recuperar los indices.[" + e.getMessage() + "]");
        throw new Exception("Error recuperando repositorio nivel agregacion[" + nivelAgregacion
                + "]. Imposible recuperar los indices.", e);
    }
    //        Para cada indice, tenemos que recoger todos los odes.
    if (indices == null || indices.length == 0) {
        logger.error("Error recuperando repositorio nivel agregacion[" + nivelAgregacion
                + "]. No existen indices en el indexador. Imposible continuar.");
        throw new Exception("Error recuperando repositorio nivel agregacion[" + nivelAgregacion
                + "]. No existen indices en el indexador. Imposible continuar.");
    }

    //          Configuramos la query que se va a realizar sobre el indice
    BooleanQuery andQuery = new BooleanQuery();
    //         Configuramos el valor de memoria.   
    andQuery.setMaxClauseCount(Integer.parseInt(props.getProperty("maxClauseCount")));
    logger.debug("Recuperando repositorio  nivel agregacion[" + nivelAgregacion + "].");
    //Recogemos las descripciones del objetivo y le metemos la l gica, debe tener el nivel de agregacion mayor o igual que el que me pasan
    andQuery.add(getConstantScoreRangeQuery(props.getProperty(CAMPO_NIVEL_AGREGACION), nivelAgregacionStr, MAX),
            BooleanClause.Occur.MUST);

    //         Nos recorremos todos los indices realizando la misma consulta y recopilando la informacion que saquemos de cada indice
    ArrayList resultados = new ArrayList();
    for (int i = 0; i < indices.length; i++) {
        Directory directorioIndiceSimple = this.getIndexByLanguage(indices[i].getIdentificador());
        if (directorioIndiceSimple == null) {
            logger.error("Error recuperando repositorio nivel agregacion[" + nivelAgregacion
                    + "]. Indice para idioma[" + indices[i].getIdentificador()
                    + "] no accesible. Imposible buscar.");
            throw new Exception("Error recuperando repositorio nivel agregacion[" + nivelAgregacion
                    + "]. Indice para idioma[" + indices[i].getIdentificador()
                    + "] no accesible. Imposible buscar.");
        }
        Hits hits = null;
        try {
            IndexSearcher searcher = new IndexSearcher(directorioIndiceSimple);
            searcher.setSimilarity(new DefaultSimilarity());

            hits = searcher.search(andQuery);
            //                Dejamos de aplicar el filtro de licencia. Nos interesan todos los ODEs del repositorio
            //                hits = searcher.search(andQuery, crearFiltroLicencia());
        } catch (Exception e) {
            logger.error("Error recuperando repositorio nivel agregacion[" + nivelAgregacion
                    + "]. Error buscando en indice[" + indices[i].getIdentificador() + "] con query["
                    + andQuery.toString() + "].[" + e.getCause() + "]");
            //                En el caso de que el indice de error, miro por el resto.
            //                throw new Exception("Error recuperando repositorio. Error buscando en indice["+indices[i].getIdentificador()+"] con query["+andQuery.toString()+"].",e);
        }
        if (hits != null && hits.length() > 0) {
            logger.info("Recuperando repositorio nivel agregacion[" + nivelAgregacion
                    + "]. Informacion de repositorio disponible para idioma[" + indices[i].getIdentificador()
                    + "] query[" + andQuery.toString() + "] documentos[" + hits.length() + "]");
            try {
                resultados.addAll(Arrays.asList(mapDocToRepositorio(hits)));
            } catch (RuntimeException e) {
                logger.error("Error recuperando repositorio nivel agregacion[" + nivelAgregacion
                        + "]. Error mapeando resultados para indice[" + indices[i].getIdentificador()
                        + "] con query[" + andQuery.toString() + "].[" + e.getCause() + "]");
                throw new Exception("Error recuperando repositorio nivel agregacion[" + nivelAgregacion
                        + "]. Error mapeando resultados para indice[" + indices[i].getIdentificador()
                        + "] con query[" + andQuery.toString() + "].", e);
            }
        } else {
            logger.info("Recuperando repositorio nivel agregacion[" + nivelAgregacion
                    + "]. No hay informacion de repositorio disponible para idioma["
                    + indices[i].getIdentificador() + "] query[" + andQuery.toString() + "]");
        }
    }
    return (ResultadoRepositorioVO[]) resultados.toArray(new ResultadoRepositorioVO[resultados.size()]);
}

From source file:gov.nasa.ensemble.core.plan.editor.search.PlanSearcher.java

License:Open Source License

/**
 * Constructor for PlanSearcher.//from w w  w. ja  v  a 2 s  .c  o m
 * 
 * @param dir the directory for the index location
 */
public PlanSearcher(RAMDirectory dir) {
    results = new Vector<Integer>();
    queries = new Vector<Query>();
    booleanOps = new int[32];

    /* there should not be more than 32 queries... */
    for (int i = 0; i < 32; i++) {
        booleanOps[i] = 0;
    }

    try {
        reader = IndexReader.open(dir);
        searcher = new IndexSearcher(reader);
    } catch (Exception e) {
        e.printStackTrace();
    }

    /* just in case the wildcard queries get too large */
    BooleanQuery.setMaxClauseCount(8192);
}

From source file:io.datalayer.lucene.search.LuceneSearchTest.java

License:Apache License

@Override
protected void setUp() throws Exception {
    BooleanQuery.setMaxClauseCount(10000);
    directory = FSDirectory.open(new File("/aos/aos.index/com.twitter.status.public.0"));
}

From source file:ir.ac.ut.engine.FeaturedRetriever.java

public static ScoreDoc[] search(String query, String qId, String field) throws IOException {
    float mu = (float) 1000;
    query = query.toLowerCase();//from  www.j a v  a2 s .  co  m
    BooleanQuery.setMaxClauseCount(query.length());

    Analyzer analyzer;
    if (field.equals(IndexedDocument.FIELD_REAL_ID)) {
        analyzer = new SimpleAnalyzer(Version.LUCENE_CURRENT);
    } else if (field.equals(IndexedDocument.FIELD_NAMED_ENTITIES)) {
        analyzer = (new MyAnalyzer(false)).MyNgramAnalyzer();
    } else if (field.equals(IndexedDocument.FIELD_SORTED_BIGRAMS)) {
        analyzer = (new MyAnalyzer(false)).MyNgramAnalyzer();
    } else if (field.equals(IndexedDocument.FIELD_SORTED_TRIGRAMS)) {
        analyzer = (new MyAnalyzer(false)).MyNgramAnalyzer();
    } else if (field.equals(IndexedDocument.FIELD_STOPWORDS3Gram)) {
        analyzer = (new MyAnalyzer(false)).MyNgramAnalyzer();
    } else if (field.equals(IndexedDocument.FIELD_POS3GRAM)) {
        analyzer = (new MyAnalyzer(false)).MyNgramAnalyzer();
    } else {
        analyzer = (new MyAnalyzer(false)).MyDefaultAnalyzer();
    }

    QueryParser qParser = new QueryParser(Version.LUCENE_47, field, analyzer);
    Query q = null;
    try {
        q = qParser.parse(QueryParser.escape(query));
    } catch (org.apache.lucene.queryparser.classic.ParseException e) {
        e.printStackTrace();
        System.out.println("Exceptional Query:" + qId);
        return new ScoreDoc[0];
    }

    Similarity simFunction = new LMDirichletSimilarity(mu);
    // Similarity simFunction = new BM25Similarity();
    IndexSearcher isearcher = new IndexSearcher(ireader);
    isearcher.setSimilarity(simFunction);
    TopFieldCollector tfc = TopFieldCollector.create(Sort.RELEVANCE, ireader.numDocs(), true, true, true,
            false);
    isearcher.search(q, tfc);

    TopDocs results = tfc.topDocs();
    ScoreDoc[] hits = results.scoreDocs;
    reportInTREC(hits, qId);
    return hits;
}

From source file:it.cnr.isti.hpc.dexter.lucene.LuceneHelper.java

License:Apache License

/**
 * Opens or creates a lucene index in the given directory
 * /*from   ww  w  . j a  v  a  2 s .co  m*/
 * @param wikiIdtToLuceneIdSerialization
 *            - the file containing the serialized mapping between wiki-id
 *            and Lucene documents ids
 * 
 * @param indexPath
 *            - the path of the directory with the Lucene's index
 */
protected LuceneHelper(File wikiIdtToLuceneIdSerialization, File indexPath) {
    logger.info("opening lucene index in folder {}", indexPath);
    config = new IndexWriterConfig(Version.LUCENE_41, ANALYZER);
    this.wikiIdtToLuceneIdSerialization = wikiIdtToLuceneIdSerialization;

    BooleanQuery.setMaxClauseCount(1000);

    try {
        index = FSDirectory.open(indexPath);
        // writer.commit();
    } catch (Exception e) {
        logger.error("opening the index: {}", e.toString());
        System.exit(1);
    }

    summarizer = new ArticleSummarizer();
    writer = getWriter();
    collectionSize = writer.numDocs();
    wikiIdToLuceneId = Collections.emptyMap();
}

From source file:it.doqui.index.ecmengine.business.personalization.multirepository.index.lucene.RepositoryAwareAbstractLuceneIndexerAndSearcherFactory.java

License:Open Source License

/**
 * Set the max number of queries in a llucen boolean query
 *
 * @param queryMaxClauses/*from w w  w .j  av  a 2s  .c  o  m*/
 */
public void setQueryMaxClauses(int queryMaxClauses) {
    this.queryMaxClauses = queryMaxClauses;
    BooleanQuery.setMaxClauseCount(this.queryMaxClauses);
}

From source file:it.unibz.instasearch.indexing.Searcher.java

License:Open Source License

private Query parseSearchQuery(SearchQuery searchQuery, IndexReader reader, boolean exact, boolean prefix)
        throws ParseException, IOException {
    String searchString = searchQuery.getSearchString();

    BooleanQuery.setMaxClauseCount(5000); // so we don't get TooManyClauses exceptions

    Query exactQuery = createExactQuery(searchQuery);
    Query returnQuery;/*  w ww .j a v  a2  s.  c o m*/

    if (exact) // want exact search, use KeywordAnalyzer
    {
        returnQuery = exactQuery;
    } else {
        Query query = parserSearchString(searchString, queryAnalyzer);
        exactQuery.setBoost(query.getBoost() * 2f); // exact query more important
        returnQuery = combineQueries(query, exactQuery);
    }

    returnQuery = rewriteQuery(searchQuery, prefix, returnQuery);

    debug("q: ", returnQuery, " - exact ", exact);

    returnQuery = returnQuery.rewrite(reader); // lucene's rewrite (ie expand prefix queries)

    return returnQuery;
}