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:es.pode.indexador.negocio.servicios.busqueda.SrvBuscadorServiceImpl.java

License:Open Source License

/**
 * Este metodo busca los documentos que tienen fecha entre las fechas desde y hasta dados y que tengan el campo de arbol curricular
 *  nodo coincidente con el identificador de nodo que le pasan. 
 * Esto devuelve el numero de documentos indexados que estan catalogados exactamente en ese nodo de arbol curricular.
 * @param idNodo Identificador del nodo de arbol curricular del que se quiere averiguar el numero de documentos que tiene asociados.
 * @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.
 *///from   w  w  w.j  a v a  2s. c  om
protected ResultadosCountVO handleBusquedaDocsNodoFechaArbolCurricular(String idNodo, Calendar fechaDesde,
        Calendar fechaHasta, String idioma) throws Exception {
    if (idNodo == null || idNodo.equals("")) {
        logger.error("Error buscando nodo de arbol curricular. Nodo vacio.");
        throw new Exception("Error buscando nodo de arbol curricular. Nodo vacio.");
    }
    if (idioma == null || idioma.equals("")) {
        logger.error("Error buscando nodo de arbol curricular. Idioma de busqueda vacio.");
        throw new Exception("Error buscando nodo de arbol curricular. Idioma de busqueda vacio.");
    }
    if (fechaDesde == null || fechaHasta == null) {
        logger.error("Error buscando nodo de arbol curricular. Fechas desde[" + fechaDesde == null ? null
                : fechaDesde.toString() + "] y hasta[" + fechaHasta == null ? null
                        : fechaHasta.toString() + "] vacias.");
        throw new Exception("Error buscando nodo de arbol curricular. Fechas desde[" + fechaDesde == null ? null
                : fechaDesde.toString() + "] y hasta[" + fechaHasta == null ? null
                        : fechaHasta.toString() + "] vacias.");
    }
    if (fechaDesde.after(fechaHasta)) {
        logger.error("Error buscando nodo de arbol curricular. Fechas desde[" + fechaDesde.toString()
                + "] y hasta[" + fechaHasta.toString() + "] incoherentes.");
        throw new Exception("Error buscando nodo de arbol curricular. 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 nodo de arbol curricular[" + idNodo + "] 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 del nodo
    andQuery.add(getTermQuery(props.getProperty(CAMPO_AREA_CURRICULAR_NODO), idNodo), 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 nodo de arbol curricular. Indice para idioma[" + idioma
                + "] no accesible. Imposible buscar.");
        throw new Exception("Error buscando nodo de arbol curricular. 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 nodo de arbol curricular. Error buscando en indice[" + idioma
                + "] con query[" + andQuery.toString() + "].[" + e.getCause() + "]");
        throw new Exception("Error buscando nodo de arbol curricular. 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;
}

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

License:Open Source License

/**
 * Este metodo busca los documentos indexados que cumplan estar en el rango de valoraciones que le pasan dentro de las fechas desde y hasta.
 * @param nivelAgregacion Valor de valoracion.
 * @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.
 */// www .  j ava  2  s  . c  o  m
protected ResultadosCountVO handleBusquedaDocsRangoFechaNivelAgregacion(String nivelAgregacion,
        Calendar fechaDesde, Calendar fechaHasta, String idioma) throws Exception {
    if (nivelAgregacion == null || nivelAgregacion.equals("")) {
        logger.error("Error buscando documentos con rango de valoracion. Nivel de agregacion vacio.");
        throw new Exception("Error buscando documentos con rango de valoracion. Nivel de agregacion vacio.");
    }
    if (idioma == null || idioma.equals("")) {
        logger.error("Error buscando documentos con rango de valoracion. Idioma de busqueda vacio.");
        throw new Exception("Error buscando documentos con rango de valoracion. Idioma de busqueda vacio.");
    }
    if (fechaDesde == null || fechaHasta == null) {
        logger.error(
                "Error buscando documentos con rango de valoracion. Fechas desde[" + fechaDesde == null ? null
                        : fechaDesde.toString() + "] y hasta[" + fechaHasta == null ? null
                                : fechaHasta.toString() + "] vacias.");
        throw new Exception(
                "Error buscando documentos con rango de valoracion. 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 rango de valoracion. Fechas desde[" + fechaDesde.toString()
                + "] y hasta[" + fechaHasta.toString() + "] incoherentes.");
        throw new Exception("Error buscando documentos con rango de valoracion. 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 nivel de agregacion[" + nivelAgregacion + "] 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 la valoracion
    andQuery.add(getTermQuery(props.getProperty(CAMPO_NIVEL_AGREGACION), nivelAgregacion),
            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 rango de valoracion. Indice para idioma[" + idioma
                + "] no accesible. Imposible buscar.");
        throw new Exception("Error buscando documentos con rango de valoracion. 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 rango de valoracion. Error buscando en indice[" + idioma
                + "] con query[" + andQuery.toString() + "].[" + e.getCause() + "]");
        throw new Exception("Error buscando documentos con rango de valoracion. 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;
}

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

License:Open Source License

/**
* Este metodo busca los ODEs indexados en todos los indices que cumplan las condiciones de busqueda que le pasan como parametro.
* Las fechas desde y hasta se interpretan inclusives y en el caso de no estar presentes, sin limite superior o inferior.
* @param paramBusq Parametros de busqueda.
* @return ResultadoHeaderVO[] Array de VO's que albergan los resulados de la consulta en un contenedor de Headers.
*/// www.  j  av  a 2 s.com
protected es.pode.indexador.negocio.servicios.busqueda.ResultadoHeaderVO[] handleBusquedaHeadersRepositorio(
        ParamPeriodoRepositorioVO paramBusq) throws Exception {

    if (paramBusq == null) {
        logger.error("Error obteniendo las cabeceras del repositorio. No hay parametros de busqueda.");
        throw new Exception("Error obteniendo las cabeceras del repositorio. No hay parametros de busqueda.");
    }
    Date fechaDesde = (paramBusq.getDesde() != null ? paramBusq.getDesde().getTime() : null);
    Date fechaHasta = (paramBusq.getHasta() != null ? paramBusq.getHasta().getTime() : null);
    if (fechaDesde != null && fechaHasta != null && fechaDesde.after(fechaHasta)) {
        logger.error("Error obteniendo las cabeceras del repositorio. Fechas desde[" + fechaDesde.toString()
                + "] y hasta[" + fechaHasta.toString() + "] incoherentes.");
        throw new Exception("Error obteniendo las cabeceras del repositorio. Fechas desde["
                + fechaDesde.toString() + "] y hasta[" + fechaHasta.toString() + "] incoherentes.");
    }
    //      Obtenemos todos los indices sobre los que hay objetos
    IndiceVO[] indices = new IndiceVO[0];
    try {
        indices = handleObtenerIdiomasBusqueda();
    } catch (Exception e) {
        logger.error("Error obteniendo las cabeceras del repositorio. Imposible recuperar los indices.["
                + e.getMessage() + "]");
        throw new Exception("Error obteniendo las cabeceras del repositorio. Imposible recuperar los indices.",
                e);
    }
    //     Para cada indice, tenemos que hacer un recorrido de todos los nodos del arbol y sumar el acumulado.
    if (indices == null || indices.length == 0) {
        logger.error(
                "Error obteniendo las cabeceras del repositorio. No existen indices en el indexador. Imposible continuar.");
        throw new Exception(
                "Error obteniendo las cabeceras del 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("Buscando headers en 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 obteniendo las cabeceras del repositorio. Indice para idioma["
                    + indices[i].getIdentificador() + "] no accesible. Imposible buscar.");
            throw new Exception("Error obteniendo las cabeceras del repositorio. Indice para idioma["
                    + indices[i].getIdentificador() + "] no accesible. Imposible buscar.");
        }
        Hits hits;
        try {
            IndexSearcher searcher = new IndexSearcher(directorioIndiceSimple);
            searcher.setSimilarity(new DefaultSimilarity());
            hits = searcher.search(andQuery);
            //             Ahora llamamos a la busqueda en repositorio pero aplicando un filtro de licencia
            //             hits = searcher.search(andQuery, crearFiltroLicencia());
        } catch (Exception e) {
            logger.error("Error obteniendo las cabeceras del repositorio. Error buscando en indice["
                    + indices[i].getIdentificador() + "] con query[" + andQuery.toString() + "].["
                    + e.getCause() + "]");
            throw new Exception("Error obteniendo las cabeceras del repositorio. Error buscando en indice["
                    + indices[i].getIdentificador() + "] con query[" + andQuery.toString() + "].", e);
        }
        if (hits != null && hits.length() > 0) {
            try {
                resultados.addAll(Arrays.asList(mapDocToHeader(hits)));
            } catch (RuntimeException e) {
                logger.error(
                        "Error obteniendo las cabeceras del repositorio. Error mapeando resultados para indice["
                                + indices[i].getIdentificador() + "] con query[" + andQuery.toString() + "].["
                                + e.getCause() + "]");
                throw new Exception(
                        "Error obteniendo las cabeceras del repositorio. Error mapeando resultados para indice["
                                + indices[i].getIdentificador() + "] con query[" + andQuery.toString() + "].",
                        e);
            }
        }
    }
    return (ResultadoHeaderVO[]) resultados.toArray(new ResultadoHeaderVO[0]);
}

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

License:Open Source License

/**
* Metodo que ejecuta una busqueda en todo el repositorio con los parametros de busqueda que le pasan.
* Las fechas desde y hasta se interpretan inclusives y en el caso de no estar presentes, sin limite superior o inferior.
* @param paramBusq Parametros de busqueda.
* @return ResultadoRecordVO[] Array de VO's que albergan los resulados de la consulta en un contenedor de Records.
*//*from  w  w w .  j  a  v a2s.c  om*/
protected es.pode.indexador.negocio.servicios.busqueda.ResultadoRecordVO[] handleBusquedaRepositorio(
        ParamPeriodoRepositorioVO paramBusq) throws Exception {
    if (paramBusq == null) {
        logger.error("Error obteniendo los registros del repositorio. No hay parametros de busqueda.");
        throw new Exception("Error obteniendo los registros del repositorio. No hay parametros de busqueda.");
    }
    Date fechaDesde = (paramBusq.getDesde() != null ? paramBusq.getDesde().getTime() : null);
    Date fechaHasta = (paramBusq.getHasta() != null ? paramBusq.getHasta().getTime() : null);
    if (fechaDesde != null && fechaHasta != null && fechaDesde.after(fechaHasta)) {
        logger.error("Error obteniendo los registros del repositorio. Fechas desde[" + fechaDesde.toString()
                + "] y hasta[" + fechaHasta.toString() + "] incoherentes.");
        throw new Exception("Error obteniendo los registros del repositorio. Fechas desde["
                + fechaDesde.toString() + "] y hasta[" + fechaHasta.toString() + "] incoherentes.");
    }
    //      Obtenemos todos los indices sobre los que hay objetos
    IndiceVO[] indices = new IndiceVO[0];
    try {
        indices = handleObtenerIdiomasBusqueda();
    } catch (Exception e) {
        logger.error("Error obteniendo los registros del repositorio. Imposible recuperar los indices.["
                + e.getMessage() + "]");
        throw new Exception("Error obteniendo los registros del repositorio. Imposible recuperar los indices.",
                e);
    }
    //     Para cada indice, tenemos que hacer un recorrido de todos los nodos del arbol y sumar el acumulado.
    if (indices == null || indices.length == 0) {
        logger.error(
                "Error obteniendo los registros del repositorio. No existen indices en el indexador. Imposible continuar.");
        throw new Exception(
                "Error obteniendo los registros del 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("Buscando registros en 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 obteniendo los registros del repositorio. Indice para idioma["
                    + indices[i].getIdentificador() + "] no accesible. Imposible buscar.");
            throw new Exception("Error obteniendo los registros del repositorio. Indice para idioma["
                    + indices[i].getIdentificador() + "] no accesible. Imposible buscar.");
        }
        Hits hits;
        try {
            IndexSearcher searcher = new IndexSearcher(directorioIndiceSimple);
            searcher.setSimilarity(new DefaultSimilarity());
            hits = searcher.search(andQuery);
            //             Ahora llamamos a la busqueda en repositorio pero aplicando un filtro de licencia
            //             hits = searcher.search(andQuery, crearFiltroLicencia());
        } catch (Exception e) {
            logger.error("Error obteniendo los registros del repositorio. Error buscando en indice["
                    + indices[i].getIdentificador() + "] con query[" + andQuery.toString() + "].["
                    + e.getCause() + "]");
            throw new Exception("Error obteniendo los registros del repositorio. Error buscando en indice["
                    + indices[i].getIdentificador() + "] con query[" + andQuery.toString() + "].", e);
        }
        if (hits != null && hits.length() > 0) {
            try {
                resultados.addAll(Arrays.asList(mapDocToRecord(hits)));
            } catch (RuntimeException e) {
                logger.error(
                        "Error obteniendo los registros del repositorio. Error mapeando resultados para indice["
                                + indices[i].getIdentificador() + "] con query[" + andQuery.toString() + "].["
                                + e.getCause() + "]");
                throw new Exception(
                        "Error obteniendo los registros del repositorio. Error mapeando resultados para indice["
                                + indices[i].getIdentificador() + "] con query[" + andQuery.toString() + "].",
                        e);
            }
        }
    }
    return (ResultadoRecordVO[]) resultados.toArray(new ResultadoRecordVO[resultados.size()]);
}

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.
*//* ww w  .j  a  va 2  s  . com*/
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 internaBusquedaSimple(es.pode.indexador.negocio.servicios.busqueda.ParamSimpleVO paramBusq,
        DisjunctionMaxQuery query) throws Exception {
    Directory directorioIndiceSimple = this.getIndexByLanguage(paramBusq.getIdiomaBusqueda());
    IndexSearcher searcher = null;
    try {//from w  w  w .  ja va  2 s.  c  o m
        searcher = new IndexSearcher(directorioIndiceSimple);
    } catch (java.io.FileNotFoundException iO) {
        throw new java.io.FileNotFoundException("Fichero lom-es no disponible");
    }

    searcher.setSimilarity(new DefaultSimilarity());
    List palabras = devolverFrases(paramBusq.getPalabrasClave().trim(), paramBusq.getIdiomaBusqueda());
    String[] claves = props.getProperty(CAMPOS_CLAVE_SIMPLE).split(SEPARADOR_CLAVES);
    for (int i = 0; i < palabras.size(); i++) {
        for (int j = 0; j < claves.length; j++) {
            query.add((List.class.isInstance(palabras.get(i)))
                    ? getQuery(palabras.get(i), claves[j], CAMPOS_PHRASE_SIMPLE)
                    : getQuery(palabras.get(i).toString(), claves[j], CAMPOS_WILDCARD_SIMPLE));
        }
    }
    if (logger.isDebugEnabled())
        logger.debug("Consulta interna simple con query[" + query.toString() + "]");
    Hits hits = searcher.search(query);
    return hits;
}

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

License:Open Source License

private Hits internaBusquedaNodo(
        es.pode.indexador.negocio.servicios.busqueda.ParamNodoArbolCurricularVO paramBusq,
        DisjunctionMaxQuery query) throws Exception {
    Directory directorioIndiceSimple = this.getIndexByLanguage(paramBusq.getIdiomaBusqueda());
    IndexSearcher searcher = new IndexSearcher(directorioIndiceSimple);
    searcher.setSimilarity(new DefaultSimilarity());
    query.add(getTermQuery(props.getProperty(CAMPO_AREA_CURRICULAR), paramBusq.getAreaCurricular()));
    if (logger.isDebugEnabled())
        logger.debug("Consulta interna nodo arbol curricular con query[" + query.toString() + "]");
    Hits hits = searcher.search(query);/*  www. ja  v a 2 s.co m*/
    return hits;
}

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

License:Open Source License

private Hits internaBusquedaMEC(String mec, String idioma, DisjunctionMaxQuery query) throws Exception {
    Directory directorioIndiceSimple = this.getIndexByLanguage(idioma);
    IndexSearcher searcher = new IndexSearcher(directorioIndiceSimple);
    searcher.setSimilarity(new DefaultSimilarity());
    query.add(getTermQuery(props.getProperty("campo_identificadorODE"), mec));
    if (logger.isDebugEnabled())
        logger.debug("Consulta MEC con query[" + query.toString() + "]");
    Hits hits = searcher.search(query);/*from   w w  w.  ja  v a2 s  .c  o  m*/
    return hits;
}

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 . j a v a2  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:es.pode.indexador.negocio.servicios.busqueda.SrvBuscadorServiceImpl.java

License:Open Source License

/**
 * @see es.pode.indexador.negocio.servicios.busqueda.SrvBuscadorService#busquedaLOM_ESVSQL(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 ww  . j  av  a  2 s. c o  m
protected DocumentosLOM_ESVO handleBusquedaLOM_ESVSQL(QuerySimpleVO paramBusqueda) throws Exception {
    DocumentosLOM_ESVO respuesta = new DocumentosLOM_ESVO();
    DocLOM_ESVO[] resultados = null;
    DisjunctionMaxQuery query = new DisjunctionMaxQuery(0.01f);
    String queryLang = paramBusqueda.getLenguajeQuery();
    String idioma = paramBusqueda.getIdioma();
    String unparsedQuery = paramBusqueda.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 + "] con longitud [" + terms.length);
        BooleanQuery query3 = new BooleanQuery();
        for (int i = 0; i < terms.length; i++) {
            BooleanQuery query2 = new BooleanQuery();
            if (this.contains(terms[i], ASTERISK) || this.contains(terms[i], QUESTIONMARK)) {
                if (logger.isDebugEnabled())
                    logger.debug("Esta query es una WildCardQUery");
                query2.add(getWildcardQuery(props.getProperty("campo_titulo"), terms[i].toLowerCase()),
                        BooleanClause.Occur.SHOULD);
                query2.add(getWildcardQuery(props.getProperty("campo_descripcion"), terms[i].toLowerCase()),
                        BooleanClause.Occur.SHOULD);
                query2.add(getWildcardQuery(props.getProperty("campo_palabrasClave"), terms[i].toLowerCase()),
                        BooleanClause.Occur.SHOULD);
            } else {
                if (logger.isDebugEnabled())
                    logger.debug("Es una query sin WildCardQuery");
                query2.add(getTermQuery(props.getProperty("campo_titulo"), terms[i].toLowerCase()),
                        BooleanClause.Occur.SHOULD);
                query2.add(getTermQuery(props.getProperty("campo_descripcion"), terms[i].toLowerCase()),
                        BooleanClause.Occur.SHOULD);
                query2.add(getTermQuery(props.getProperty("campo_palabrasClave"), terms[i].toLowerCase()),
                        BooleanClause.Occur.SHOULD);
            }
            query3.add(query2, BooleanClause.Occur.MUST);
        }
        query.add(query3);
        if (logger.isDebugEnabled())
            logger.debug("Consulta LOM_ES con query[" + query + "] a partir de SQUI 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);
                //               lom = this.getLom(manifest.getMetadata(), manifest.getIdentifier());
                //               lomCastor = (es.pode.parseadorXML.lomes.Lom) beanMapper
                //                     .map(lom, es.pode.parseadorXML.lomes.Lom.class);
                LomAgrega agrega = new LomAgrega(lom);
                TechnicalAgrega tecnica = agrega.getTechnicalAgrega();
                ArrayList localizadores = new ArrayList();
                String hostNodo = AgregaPropertiesImpl.getInstance().getProperty(KEY_HOST_NODO);
                String local = props.getProperty(PROTOCOLO_HTTP) + hostNodo + props.getProperty(BUSCADOR_FICHA)
                        + idioma + props.getProperty(BARRA) + manifest.getIdentifier();
                localizadores.add(local);
                tecnica.setLocalizadorAv(localizadores);
                agrega.setTechnicalAgrega(tecnica);
                lom = agrega.getLom();
                //               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;
}