Example usage for org.apache.lucene.search Sort Sort

List of usage examples for org.apache.lucene.search Sort Sort

Introduction

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

Prototype

public Sort(SortField... fields) 

Source Link

Document

Sets the sort to the given criteria in succession: the first SortField is checked first, but if it produces a tie, then the second SortField is used to break the tie, etc.

Usage

From source file:com.pjaol.search.test.UnitTests.TestCartesian.java

License:Apache License

public void testRange() throws IOException, InvalidGeoException {
    searcher = new IndexSearcher(directory);

    final double miles = 6.0;

    // create a distance query
    final DistanceQuery dq = new DistanceQuery(lat, lng, miles, latField, lngField, true);

    System.out.println(dq);// w w w. j a  va  2  s.c  o  m
    //create a term query to search against all documents
    Query tq = new TermQuery(new Term("metafile", "doc"));

    FieldScoreQuery fsQuery = new FieldScoreQuery("geo_distance", Type.FLOAT);
    CustomScoreQuery customScore = new CustomScoreQuery(tq, fsQuery) {

        public float customScore(int doc, float subQueryScore, float valSrcScore) {
            System.out.println(doc);
            if (dq.distanceFilter.getDistance(doc) == null)
                return 0;

            double distance = (double) dq.distanceFilter.getDistance(doc);
            // boost score shouldn't exceed 1
            if (distance < 1.0d)
                distance = 1.0d;
            //boost by distance is invertly proportional to
            // to distance from center point to location
            float score = new Float((miles - distance) / miles).floatValue();
            return score * subQueryScore;
        }
    };
    // Create a distance sort
    // As the radius filter has performed the distance calculations
    // already, pass in the filter to reuse the results.
    // 
    DistanceSortSource dsort = new DistanceSortSource(dq.distanceFilter);
    Sort sort = new Sort(new SortField("foo", dsort));

    // Perform the search, using the term query, the serial chain filter, and the
    // distance sort
    Hits hits = searcher.search(customScore, dq.getFilter()); //,sort);

    int results = hits.length();

    // Get a list of distances 
    Map<Integer, Double> distances = dq.distanceFilter.getDistances();

    // distances calculated from filter first pass must be less than total
    // docs, from the above test of 20 items, 12 will come from the boundary box
    // filter, but only 5 are actually in the radius of the results.

    // Note Boundary Box filtering, is not accurate enough for most systems.

    System.out.println("Distance Filter filtered: " + distances.size());
    System.out.println("Results: " + results);
    System.out.println("=============================");
    System.out.println("Distances should be 14 " + distances.size());
    System.out.println("Results should be 7 " + results);

    assertEquals(14, distances.size());
    assertEquals(7, results);

    for (int i = 0; i < results; i++) {
        Document d = hits.doc(i);

        String name = d.get("name");
        double rsLat = NumberUtils.SortableStr2double(d.get(latField));
        double rsLng = NumberUtils.SortableStr2double(d.get(lngField));
        Double geo_distance = distances.get(hits.id(i));

        double distance = DistanceUtils.getDistanceMi(lat, lng, rsLat, rsLng);
        double llm = DistanceUtils.getLLMDistance(lat, lng, rsLat, rsLng);
        System.out.println("Name: " + name + ", Distance (res, ortho, harvesine):" + distance + " |"
                + geo_distance + "|" + llm + " | score " + hits.score(i));
        assertTrue(Math.abs((distance - llm)) < 1);
        assertTrue((distance < miles));
    }
}

From source file:com.pjaol.search.test.UnitTests.TestDistance.java

License:Apache License

public void testRange() throws IOException, InvalidGeoException {
    searcher = new IndexSearcher(directory);

    double miles = 6.0;

    // create a distance query
    DistanceQuery dq = new DistanceQuery(lat, lng, miles, latField, lngField, false);

    System.out.println(dq.latFilter.toString() + " " + dq.lngFilter);

    //create a term query to search against all documents
    Query tq = new TermQuery(new Term("metafile", "doc"));

    // Create a distance sort
    // As the radius filter has performed the distance calculations
    // already, pass in the filter to reuse the results.
    // /* w  w w  . j  av  a  2 s . com*/
    DistanceSortSource dsort = new DistanceSortSource(dq.distanceFilter);
    Sort sort = new Sort(new SortField("foo", dsort));

    // Perform the search, using the term query, the serial chain filter, and the
    // distance sort
    Hits hits = searcher.search(tq, dq.getFilter(), sort);

    int results = hits.length();

    // Get a list of distances 
    Map<Integer, Double> distances = dq.distanceFilter.getDistances();

    // distances calculated from filter first pass must be less than total
    // docs, from the above test of 20 items, 12 will come from the boundary box
    // filter, but only 5 are actually in the radius of the results.

    // Note Boundary Box filtering, is not accurate enough for most systems.

    System.out.println("Distance Filter filtered: " + distances.size());
    System.out.println("Results: " + results);
    System.out.println("=============================");
    assertEquals(7, distances.size());
    assertEquals(7, results);

    for (int i = 0; i < results; i++) {
        Document d = hits.doc(i);

        String name = d.get("name");
        double rsLat = NumberUtils.SortableStr2double(d.get(latField));
        double rsLng = NumberUtils.SortableStr2double(d.get(lngField));
        Double geo_distance = distances.get(hits.id(i));

        double distance = DistanceUtils.getDistanceMi(lat, lng, rsLat, rsLng);
        double llm = DistanceUtils.getLLMDistance(lat, lng, rsLat, rsLng);
        System.out.println("Name: " + name + ", Distance (res, ortho, harvesine):" + distance + " |"
                + geo_distance + "|" + llm);
        assertTrue(Math.abs((distance - llm)) < 1);
        assertTrue((distance < miles));
    }
}

From source file:com.qwazr.search.field.SortUtils.java

License:Apache License

final public static Sort buildSort(Map<String, FieldTypeInterface> fields,
        LinkedHashMap<String, QueryDefinition.SortEnum> sorts) {
    if (sorts.isEmpty())
        return null;
    final SortField[] sortFields = new SortField[sorts.size()];
    int i = 0;//from w w  w  .j a  v a2 s  .co m
    for (Map.Entry<String, QueryDefinition.SortEnum> sort : sorts.entrySet())
        sortFields[i++] = buildSortField(fields, sort.getKey(), sort.getValue());
    if (sortFields.length == 1)
        return new Sort(sortFields[0]);
    return new Sort(sortFields);
}

From source file:com.soebes.supose.core.search.SearchRepository.java

License:Open Source License

public TopDocs getQueryResult(String queryLine) {
    IndexReader reader = null;/*from  w  w  w .j a v  a 2s . c o m*/
    TopDocs result = null;
    try {

        reader = IndexReader.open(getIndexDirectory());
        setReader(reader);

        BooleanQuery.setMaxClauseCount(Integer.MAX_VALUE);
        Searcher searcher = new IndexSearcher(reader);
        setSearcher(searcher);
        SortField[] sf = { new SortField(FieldNames.REVISION.toString()),
                new SortField(FieldNames.FILENAME.toString()), // We use for
                                                                                                                                 // sorting
                                                                                                                                 // the
                                                                                                                                 // filename
        };
        Sort sort = new Sort(sf);
        // Here we define the default field for searching.
        QueryParser parser = new CustomQueryParser(FieldNames.CONTENTS.toString(), getAnalyzer());
        // We will allow using a wildcard at the beginning of the
        // expression.
        parser.setAllowLeadingWildcard(true);
        // The search term will not be expanded to lowercase.
        parser.setLowercaseExpandedTerms(true);
        Query query = parser.parse(queryLine);
        LOGGER.info("Query: " + query.toString());
        // That's not the best idea...but currently i have not better
        // solution for this...
        // This is intended to get all results not only a limited number
        // results.
        TopDocs tmp = searcher.search(query, null, 20, sort);
        result = searcher.search(query, null, tmp.totalHits, sort);
    } catch (CorruptIndexException e) {
        LOGGER.error("Error: The index is corrupted: ", e);
    } catch (IOException e) {
        LOGGER.error("Error: IOException: ", e);
    } catch (Exception e) {
        LOGGER.error("Error: Something has gone wrong: ", e);
    }
    return result;
}

From source file:com.square.core.dao.implementations.PersonneMoraleDaoImplementation.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public ResultatPaginationFullText<PersonneMorale> rechercherPersonneMoraleParCriteres(
        RemotePagingCriteriasDto<PersonneMoralCriteresRechercheDto> criteres) throws ParseException {

    final PersonneMoralCriteresRechercheDto criteresRecherche = criteres.getCriterias();

    final BooleanQuery bq = new BooleanQuery();

    if (criteresRecherche.getRaisonSociale() != null && !("".equals(criteresRecherche.getRaisonSociale()))) {
        final AnalysingCustomQueryParser parser = new AnalysingCustomQueryParser(getMatchingVersion(),
                "raisonSociale", getAnalyser(PersonneMorale.class));
        parser.setAllowLeadingWildcard(true);
        final String raisonSociale = criteresRecherche.getRaisonSociale().replaceAll(POURCENT, ETOILE);
        final org.apache.lucene.search.Query requeteLucene = parser
                .parse(raisonSociale.lastIndexOf(ETOILE) == raisonSociale.length() - 1 ? raisonSociale
                        : raisonSociale + ETOILE);
        bq.add(requeteLucene, BooleanClause.Occur.MUST);
    }/*from  w  ww.j  a va2 s .  c  o  m*/
    if (criteresRecherche.getEnseigneCommerciale() != null
            && !("".equals(criteresRecherche.getEnseigneCommerciale()))) {
        final AnalysingCustomQueryParser parser = new AnalysingCustomQueryParser(getMatchingVersion(),
                "enseigneCommercial", getAnalyser(PersonneMorale.class));
        parser.setAllowLeadingWildcard(true);
        final String enseigneCommerciale = criteresRecherche.getEnseigneCommerciale().replaceAll(POURCENT,
                ETOILE);
        final org.apache.lucene.search.Query requeteLucene = parser
                .parse(enseigneCommerciale.lastIndexOf(ETOILE) == enseigneCommerciale.length() - 1
                        ? enseigneCommerciale
                        : enseigneCommerciale + ETOILE);
        bq.add(requeteLucene, BooleanClause.Occur.MUST);
    }
    // Critre sur le numro de l'entreprise
    String numeroEntreprise = criteresRecherche.getNumeroEntreprise();
    if (!StringUtils.isBlank(numeroEntreprise)) {
        numeroEntreprise = numeroEntreprise.replaceAll(POURCENT, ETOILE);
        final MultiFieldQueryParser parser = new MultiFieldQueryParser(getMatchingVersion(),
                new String[] { "numSiret", "num" }, getAnalyser(PersonneMorale.class));
        parser.setAllowLeadingWildcard(true);
        final org.apache.lucene.search.Query requeteLucene = parser.parse(numeroEntreprise);
        bq.add(requeteLucene, BooleanClause.Occur.MUST);
    }
    // Critere sur le complement du nom
    if (criteresRecherche.getComplementNom() != null && !("".equals(criteresRecherche.getComplementNom()))) {
        final AnalysingCustomQueryParser parser = new AnalysingCustomQueryParser(getMatchingVersion(),
                "adresses.complementNom", getAnalyser(PersonneMorale.class));
        parser.setAllowLeadingWildcard(true);
        final String complementNom = criteresRecherche.getComplementNom().replaceAll(POURCENT, ETOILE);
        final org.apache.lucene.search.Query requeteLucene = parser
                .parse(complementNom.lastIndexOf(ETOILE) == complementNom.length() - 1 ? complementNom
                        : complementNom + ETOILE);
        bq.add(requeteLucene, BooleanClause.Occur.MUST);
    }
    // Critre sur le dpartement
    if (criteresRecherche.getListeDepartements() != null
            && !criteresRecherche.getListeDepartements().isEmpty()) {
        final List<String> listeValeurs = (List<String>) CollectionUtils
                .collect(criteresRecherche.getListeDepartements(), StringValueTransformer.getInstance());
        bq.add((Query) getInQuery("adresses.codePostalCommune.commune.departement.id", listeValeurs),
                BooleanClause.Occur.MUST);
    }
    // Critre sur la ville
    if (criteresRecherche.getListeVilles() != null && !criteresRecherche.getListeVilles().isEmpty()) {
        final List<String> listeValeurs = (List<String>) CollectionUtils
                .collect(criteresRecherche.getListeVilles(), StringValueTransformer.getInstance());
        bq.add((Query) getInQuery("adresses.codePostalCommune.commune.id", listeValeurs),
                BooleanClause.Occur.MUST);
    }
    // Critre sur le code postal
    if (criteresRecherche.getListeCodesPostaux() != null
            && !criteresRecherche.getListeCodesPostaux().isEmpty()) {
        final List<String> listeValeurs = (List<String>) CollectionUtils
                .collect(criteresRecherche.getListeCodesPostaux(), StringValueTransformer.getInstance());
        bq.add((Query) getInQuery("adresses.codePostalCommune.codePostal.id", listeValeurs),
                BooleanClause.Occur.MUST);
    }
    // Critre sur la forme juridique
    if (criteresRecherche.getListeFormesJuridiques() != null
            && !criteresRecherche.getListeFormesJuridiques().isEmpty()) {
        final List<String> listeValeurs = (List<String>) CollectionUtils
                .collect(criteresRecherche.getListeFormesJuridiques(), StringValueTransformer.getInstance());
        bq.add((Query) getInQuery("formeJuridique.id", listeValeurs), BooleanClause.Occur.MUST);
    }
    // Critre sur le commercial
    if (criteresRecherche.getListeCommerciaux() != null && !criteresRecherche.getListeCommerciaux().isEmpty()) {
        final List<String> listeValeurs = (List<String>) CollectionUtils
                .collect(criteresRecherche.getListeCommerciaux(), StringValueTransformer.getInstance());
        bq.add((Query) getInQuery("attribution.ressource.id", listeValeurs), BooleanClause.Occur.MUST);
    }
    // Critre sur l'agence
    if (criteresRecherche.getListeAgences() != null && !criteresRecherche.getListeAgences().isEmpty()) {
        final List<String> listeValeurs = (List<String>) CollectionUtils
                .collect(criteresRecherche.getListeAgences(), StringValueTransformer.getInstance());
        bq.add(getInQuery("attribution.agence.id", listeValeurs), BooleanClause.Occur.MUST);
    }
    // Critre sur la nature
    if (criteresRecherche.getListeNatures() != null && !criteresRecherche.getListeNatures().isEmpty()) {
        final List<String> listeValeurs = (List<String>) CollectionUtils
                .collect(criteresRecherche.getListeNatures(), StringValueTransformer.getInstance());
        bq.add((Query) getInQuery("naturePersonneMorale.id", listeValeurs), BooleanClause.Occur.MUST);
    }

    // Construction de la requte par defaut.
    if (criteresRecherche.getRaisonSociale() == null || "".equals(criteresRecherche.getRaisonSociale())) {
        final QueryParser parser = new QueryParser(getMatchingVersion(), "raisonSociale",
                getAnalyser(PersonnePhysique.class));
        parser.setAllowLeadingWildcard(true);
        final org.apache.lucene.search.Query requeteLucene = parser.parse("*");
        bq.add(requeteLucene, BooleanClause.Occur.MUST);
    }

    // CONSTRUCTION DE LA REQUETE
    final FullTextQuery fullTextQuery = createFullTextQuery(bq, PersonneMorale.class);

    // AJOUT DES INFORMATION DE TRI
    if (criteres.getListeSorts().size() > 0) {
        final SortField[] listeChamp = new SortField[criteres.getListeSorts().size()];
        for (int index = 0; index < criteres.getListeSorts().size(); index++) {
            listeChamp[index] = new SortField(criteres.getListeSorts().get(index).getSortField(),
                    SortField.STRING, criteres.getListeSorts().get(index)
                            .getSortAsc() == RemotePagingSort.REMOTE_PAGING_SORT_DESC);
        }
        final Sort sort = new Sort(listeChamp);
        fullTextQuery.setSort(sort);
    }

    // AJOUT DES INFORMATIONS DE PAGINATION
    fullTextQuery.setFirstResult(criteres.getFirstResult());
    fullTextQuery.setMaxResults(criteres.getMaxResult());

    // RETOURNE LA LISTE DES RESULTATS ET LE NOMBRE TOTAL DE RESULTAT (non affct par la pagination)
    return new ResultatPaginationFullText<PersonneMorale>(fullTextQuery.list(), fullTextQuery.getResultSize());
}

From source file:com.square.core.dao.implementations.PersonnePhysiqueDaoImplementation.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override//  ww w  . j a  v a  2s . com
public ResultatPaginationFullText<PersonnePhysique> rechercheFullTextPersonne(
        RemotePagingCriteriasDto<PersonneCriteresRechercheDto> criteres) throws ParseException {

    final PersonneCriteresRechercheDto criteresRecherche = criteres.getCriterias();

    // Si des critres ont t fournis on traite ces critres
    final BooleanQuery bq = new BooleanQuery();

    if (criteresRecherche.getNumeroClient() != null && !("".equals(criteresRecherche.getNumeroClient()))) {
        final AnalysingCustomQueryParser parser = new AnalysingCustomQueryParser(getMatchingVersion(), "num",
                getAnalyser(PersonnePhysique.class));
        parser.setAllowLeadingWildcard(true);
        String numeroClient = criteresRecherche.getNumeroClient().replaceAll(POURCENT, ETOILE);
        if (!criteres.getCriterias().isRechercheStricte()) {
            numeroClient = numeroClient.lastIndexOf(ETOILE) == numeroClient.length() - 1 ? numeroClient
                    : numeroClient + ETOILE;
        }
        final org.apache.lucene.search.Query requeteLucene = parser.parse(numeroClient);
        bq.add(requeteLucene, BooleanClause.Occur.MUST);
    }
    if (criteresRecherche.getNom() != null && !("".equals(criteresRecherche.getNom()))) {
        final AnalysingCustomQueryParser parser = new AnalysingCustomQueryParser(getMatchingVersion(), "nom",
                getAnalyser(PersonnePhysique.class));
        parser.setAllowLeadingWildcard(true);
        String nom = criteresRecherche.getNom().replaceAll(POURCENT, ETOILE);
        if (!criteres.getCriterias().isRechercheStricte()) {
            nom = nom.lastIndexOf(ETOILE) == nom.length() - 1 ? nom : nom + ETOILE;
        }
        final org.apache.lucene.search.Query requeteLucene = parser.parse(nom);
        bq.add(requeteLucene, BooleanClause.Occur.MUST);
    }
    if (criteresRecherche.getNomJeuneFille() != null && !("".equals(criteresRecherche.getNomJeuneFille()))) {
        final AnalysingCustomQueryParser parser = new AnalysingCustomQueryParser(getMatchingVersion(),
                "nomJeuneFille", getAnalyser(PersonnePhysique.class));
        parser.setAllowLeadingWildcard(true);
        String nomJeuneFille = criteresRecherche.getNomJeuneFille().replaceAll(POURCENT, ETOILE);
        if (!criteres.getCriterias().isRechercheStricte()) {
            nomJeuneFille = nomJeuneFille.lastIndexOf(ETOILE) == nomJeuneFille.length() - 1 ? nomJeuneFille
                    : nomJeuneFille + ETOILE;
        }
        final org.apache.lucene.search.Query requeteLucene = parser.parse(nomJeuneFille);
        bq.add(requeteLucene, BooleanClause.Occur.MUST);
    }
    if (criteresRecherche.getPrenom() != null && !("".equals(criteresRecherche.getPrenom()))) {
        final AnalysingCustomQueryParser parser = new AnalysingCustomQueryParser(getMatchingVersion(), "prenom",
                getAnalyser(PersonnePhysique.class));
        parser.setAllowLeadingWildcard(true);
        String prenom = criteresRecherche.getPrenom().replaceAll(POURCENT, ETOILE);
        if (!criteres.getCriterias().isRechercheStricte()) {
            prenom = prenom.lastIndexOf(ETOILE) == prenom.length() - 1 ? prenom : prenom + ETOILE;
        }
        final org.apache.lucene.search.Query requeteLucene = parser.parse(prenom);
        bq.add(requeteLucene, BooleanClause.Occur.MUST);
    }
    if (criteresRecherche.getNro() != null && !("".equals(criteresRecherche.getNro()))) {
        if (criteresRecherche.getNro().length() == 15) {
            final NumeroRoDto numeroRo = squareMappingService.convertirNroVersNss(criteresRecherche.getNro());

            AnalysingCustomQueryParser parser = new AnalysingCustomQueryParser(getMatchingVersion(),
                    "infoSante.numSecuriteSocial", getAnalyser(PersonnePhysique.class));
            parser.setAllowLeadingWildcard(true);
            String numeroSs = numeroRo.getNumeroSS().replaceAll(POURCENT, ETOILE);
            if (!criteres.getCriterias().isRechercheStricte()) {
                numeroSs = numeroSs.lastIndexOf(ETOILE) == numeroSs.length() - 1 ? numeroSs : numeroSs + ETOILE;
            }
            org.apache.lucene.search.Query requeteLucene = parser.parse(numeroSs);
            bq.add(requeteLucene, BooleanClause.Occur.MUST);

            parser = new AnalysingCustomQueryParser(getMatchingVersion(), "infoSante.cleSecuriteSocial",
                    getAnalyser(PersonnePhysique.class));
            parser.setAllowLeadingWildcard(true);
            String cleSs = numeroRo.getCleSS().replaceAll(POURCENT, ETOILE);
            if (!criteres.getCriterias().isRechercheStricte()) {
                cleSs = cleSs.lastIndexOf(ETOILE) == cleSs.length() - 1 ? cleSs : cleSs + ETOILE;
            }
            requeteLucene = parser.parse(cleSs);
            bq.add(requeteLucene, BooleanClause.Occur.MUST);
        } else {
            final AnalysingCustomQueryParser parser = new AnalysingCustomQueryParser(getMatchingVersion(),
                    "infoSante.numSecuriteSocial", getAnalyser(PersonnePhysique.class));
            parser.setAllowLeadingWildcard(true);
            String numeroSs = criteresRecherche.getNro().replaceAll(POURCENT, ETOILE);
            if (!criteres.getCriterias().isRechercheStricte()) {
                numeroSs = numeroSs.lastIndexOf(ETOILE) == numeroSs.length() - 1 ? numeroSs : numeroSs + ETOILE;
            }
            final org.apache.lucene.search.Query requeteLucene = parser.parse(numeroSs);
            bq.add(requeteLucene, BooleanClause.Occur.MUST);
        }
    }

    if (criteresRecherche.getDateNaissance() != null) {
        final DateNaissanceBridge dateBridge = new DateNaissanceBridge();

        final AnalysingCustomQueryParser parser = new AnalysingCustomQueryParser(getMatchingVersion(),
                "dateNaissance", getAnalyser(PersonnePhysique.class));
        final org.apache.lucene.search.Query requeteLucene = parser
                .parse(dateBridge.objectToString(criteresRecherche.getDateNaissance()));
        bq.add(requeteLucene, BooleanClause.Occur.MUST);
    }
    if (criteresRecherche.getListeNatures() != null && !criteresRecherche.getListeNatures().isEmpty()) {
        final List<String> listeValeurs = (List<String>) CollectionUtils
                .collect(criteresRecherche.getListeNatures(), StringValueTransformer.getInstance());
        bq.add((Query) getInQuery("nature.id", listeValeurs), BooleanClause.Occur.MUST);
    }
    if (criteresRecherche.getTelephone() != null && !("".equals(criteresRecherche.getTelephone()))) {
        final AnalysingCustomQueryParser parser = new AnalysingCustomQueryParser(getMatchingVersion(),
                "telephones.numTelephone", getAnalyser(PersonnePhysique.class));
        parser.setAllowLeadingWildcard(true);
        String telephone = criteresRecherche.getTelephone().replaceAll(POURCENT, ETOILE);
        if (!criteres.getCriterias().isRechercheStricte()) {
            telephone = telephone.lastIndexOf(ETOILE) == telephone.length() - 1 ? telephone
                    : telephone + ETOILE;
        }
        final org.apache.lucene.search.Query requeteLucene = parser.parse(telephone);
        bq.add(requeteLucene, BooleanClause.Occur.MUST);
    }
    if (criteresRecherche.getEmail() != null && !("".equals(criteresRecherche.getEmail()))) {
        final AnalysingCustomQueryParser parser = new AnalysingCustomQueryParser(getMatchingVersion(),
                "emails.adresse", getAnalyser(PersonnePhysique.class));
        parser.setAllowLeadingWildcard(true);
        String email = criteresRecherche.getEmail().replaceAll(POURCENT, ETOILE);
        if (!criteres.getCriterias().isRechercheStricte()) {
            email = email.lastIndexOf(ETOILE) == email.length() - 1 ? email : email + ETOILE;
        }
        final org.apache.lucene.search.Query requeteLucene = parser.parse(email);
        bq.add(requeteLucene, BooleanClause.Occur.MUST);
    }
    if (criteresRecherche.getNumVoie() != null && !("".equals(criteresRecherche.getNumVoie()))) {
        final AnalysingCustomQueryParser parser = new AnalysingCustomQueryParser(getMatchingVersion(),
                "adresses.numeroVoie", getAnalyser(PersonnePhysique.class));
        parser.setAllowLeadingWildcard(true);
        String numVoie = criteresRecherche.getNumVoie().replaceAll(POURCENT, ETOILE);
        if (!criteres.getCriterias().isRechercheStricte()) {
            numVoie = numVoie.lastIndexOf(ETOILE) == numVoie.length() - 1 ? numVoie : numVoie + ETOILE;
        }
        final org.apache.lucene.search.Query requeteLucene = parser.parse(numVoie);
        bq.add(requeteLucene, BooleanClause.Occur.MUST);
    }
    if (criteresRecherche.getListeNaturesVoie() != null && !criteresRecherche.getListeNaturesVoie().isEmpty()) {
        final List<String> listeValeurs = (List<String>) CollectionUtils
                .collect(criteresRecherche.getListeNaturesVoie(), StringValueTransformer.getInstance());
        bq.add((Query) getInQuery("adresses.typeVoie.id", listeValeurs), BooleanClause.Occur.MUST);
    }
    if (criteresRecherche.getListeNaturesTelephones() != null
            && !criteresRecherche.getListeNaturesTelephones().isEmpty()) {
        final List<String> listeValeurs = (List<String>) CollectionUtils
                .collect(criteresRecherche.getListeNaturesTelephones(), StringValueTransformer.getInstance());
        bq.add((Query) getInQuery("telephones.natureTelephone.id", listeValeurs), BooleanClause.Occur.MUST);
    }
    if (criteresRecherche.getAdresse() != null && !("".equals(criteresRecherche.getAdresse()))) {
        final AnalysingCustomQueryParser parser = new AnalysingCustomQueryParser(getMatchingVersion(),
                "adresses.nomVoie", getAnalyser(PersonnePhysique.class));
        parser.setAllowLeadingWildcard(true);
        String adresse = criteresRecherche.getAdresse().replaceAll(POURCENT, ETOILE);
        if (!criteres.getCriterias().isRechercheStricte()) {
            adresse = adresse.lastIndexOf(ETOILE) == adresse.length() - 1 ? adresse : adresse + ETOILE;
        }
        final org.apache.lucene.search.Query requeteLucene = parser.parse(adresse);
        bq.add(requeteLucene, BooleanClause.Occur.MUST);
    }
    if (criteresRecherche.getListeCodesPostaux() != null
            && !criteresRecherche.getListeCodesPostaux().isEmpty()) {
        final List<String> listeValeurs = (List<String>) CollectionUtils
                .collect(criteresRecherche.getListeCodesPostaux(), StringValueTransformer.getInstance());
        bq.add((Query) getInQuery("adresses.codePostalCommune.codePostal.id", listeValeurs),
                BooleanClause.Occur.MUST);
    }
    if (criteresRecherche.getListeVilles() != null && !criteresRecherche.getListeVilles().isEmpty()) {
        final List<String> listeValeurs = (List<String>) CollectionUtils
                .collect(criteresRecherche.getListeVilles(), StringValueTransformer.getInstance());
        bq.add((Query) getInQuery("adresses.codePostalCommune.commune.id", listeValeurs),
                BooleanClause.Occur.MUST);
    }
    if (criteresRecherche.getIdCommerciaux() != null && !criteresRecherche.getIdCommerciaux().isEmpty()) {
        final List<String> listeValeurs = (List<String>) CollectionUtils
                .collect(criteresRecherche.getIdCommerciaux(), StringValueTransformer.getInstance());
        bq.add((Query) getInQuery("attribution.ressource.id", listeValeurs), BooleanClause.Occur.MUST);
    }
    if (criteresRecherche.getIdAgences() != null && !criteresRecherche.getIdAgences().isEmpty()) {
        final List<String> listeValeurs = (List<String>) CollectionUtils
                .collect(criteresRecherche.getIdAgences(), StringValueTransformer.getInstance());
        bq.add((Query) getInQuery("attribution.agence.id", listeValeurs), BooleanClause.Occur.MUST);
    }
    if (criteresRecherche.getIdPersonnesAIgnorer() != null
            && !criteresRecherche.getIdPersonnesAIgnorer().isEmpty()) {
        final List<String> listeValeurs = (List<String>) CollectionUtils
                .collect(criteresRecherche.getIdPersonnesAIgnorer(), StringValueTransformer.getInstance());
        bq.add((Query) getInQuery("id", listeValeurs), BooleanClause.Occur.MUST_NOT);
    }
    if (criteresRecherche.getListeReseaux() != null && !criteresRecherche.getListeReseaux().isEmpty()) {
        final List<String> listeValeurs = (List<String>) CollectionUtils
                .collect(criteresRecherche.getListeReseaux(), StringValueTransformer.getInstance());
        bq.add((Query) getInQuery("reseau.id", listeValeurs), BooleanClause.Occur.MUST);
    }
    final List<Long> idPersonnes = criteresRecherche.getIdPersonnes();
    if (idPersonnes != null && !idPersonnes.isEmpty()) {
        final List<String> listeValeurs = (List<String>) CollectionUtils.collect(idPersonnes,
                StringValueTransformer.getInstance());
        bq.add((Query) getInQuery("id", listeValeurs), BooleanClause.Occur.MUST);
    }

    // On ne recherche que les personnes non supprimes
    if (criteresRecherche.getSupprime() != null) {
        bq.add(new TermQuery(new Term("supprime", criteresRecherche.getSupprime().toString())),
                BooleanClause.Occur.MUST);
    }

    // CONSTRUCTION DE LA REQUETE
    final FullTextQuery fullTextQuery = createFullTextQuery(bq, PersonnePhysique.class);
    logger.debug("Requte full text : " + fullTextQuery.getQueryString());

    // AJOUT DES INFORMATION DE TRI
    if (criteres.getListeSorts().size() > 0) {
        final SortField[] listeChamp = new SortField[criteres.getListeSorts().size()];
        for (int index = 0; index < criteres.getListeSorts().size(); index++) {
            listeChamp[index] = new SortField(criteres.getListeSorts().get(index).getSortField(),
                    SortField.STRING, criteres.getListeSorts().get(index)
                            .getSortAsc() == RemotePagingSort.REMOTE_PAGING_SORT_DESC);
        }
        final Sort sort = new Sort(listeChamp);
        fullTextQuery.setSort(sort);

    }

    // AJOUT DES INFORMATIONS DE PAGINATION
    final int nbMaxDocs = fullTextQuery.getResultSize();
    fullTextQuery.setFirstResult(criteres.getFirstResult());
    fullTextQuery.setMaxResults((criteres.getFirstResult() + criteres.getMaxResult()) > nbMaxDocs
            ? (nbMaxDocs == 0 ? nbMaxDocs + 1 : nbMaxDocs)
            : criteres.getMaxResult());

    // RETOURNE LA LISTE DES RESULTATS ET LE NOMBRE TOTAL DE RESULTAT (non affct par la pagination)
    return new ResultatPaginationFullText<PersonnePhysique>(fullTextQuery.list(), nbMaxDocs);
}

From source file:com.square.core.dao.implementations.RessourceDaoImplementation.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override//from   w w  w  .  j  a  va 2  s  . c o  m
public ResultatPaginationFullText<Ressource> rechercherFullTextRessource(
        RemotePagingCriteriasDto<RessourceCriteresRechercheDto> criteres) throws ParseException {

    final RessourceCriteresRechercheDto criteresRecherche = criteres.getCriterias();

    // Si des critres ont t fournis on traite ces critres
    final BooleanQuery bq = new BooleanQuery();

    if (criteresRecherche.getNom() != null && !("".equals(criteresRecherche.getNom()))) {
        final AnalysingCustomQueryParser parser = new AnalysingCustomQueryParser(getMatchingVersion(),
                FIELD_NOM, getAnalyser(Ressource.class));
        parser.setAllowLeadingWildcard(true);
        final String nom = criteresRecherche.getNom().replaceAll(POURCENT, ETOILE);
        final org.apache.lucene.search.Query requeteLucene = parser
                .parse(nom.lastIndexOf(ETOILE) == nom.length() - 1 ? nom : nom + ETOILE);
        bq.add(requeteLucene, BooleanClause.Occur.MUST);
    }
    if (criteresRecherche.getPrenom() != null && !("".equals(criteresRecherche.getPrenom()))) {
        final AnalysingCustomQueryParser parser = new AnalysingCustomQueryParser(getMatchingVersion(), "prenom",
                getAnalyser(Ressource.class));
        parser.setAllowLeadingWildcard(true);
        final String prenom = criteresRecherche.getPrenom().replaceAll(POURCENT, ETOILE);
        final org.apache.lucene.search.Query requeteLucene = parser
                .parse(prenom.lastIndexOf(ETOILE) == prenom.length() - 1 ? prenom : prenom + ETOILE);
        bq.add(requeteLucene, BooleanClause.Occur.MUST);
    }
    // Critre sur la liste des services
    if (criteresRecherche.getIdServices() != null && !criteresRecherche.getIdServices().isEmpty()) {
        final List<String> listeValeurs = (List<String>) CollectionUtils
                .collect(criteresRecherche.getIdServices(), StringValueTransformer.getInstance());
        bq.add((Query) getInQuery("service.id", listeValeurs), BooleanClause.Occur.MUST);
    }
    // Critre sur la liste des fonctions
    if (criteresRecherche.getIdFonctions() != null && !criteresRecherche.getIdFonctions().isEmpty()) {
        final List<String> listeValeurs = (List<String>) CollectionUtils
                .collect(criteresRecherche.getIdFonctions(), StringValueTransformer.getInstance());
        bq.add((Query) getInQuery("fonction.id", listeValeurs), BooleanClause.Occur.MUST);
    }
    // Critre sur la liste des etats
    if (criteresRecherche.getIdEtats() != null && !criteresRecherche.getIdEtats().isEmpty()) {
        final List<String> listeValeurs = (List<String>) CollectionUtils.collect(criteresRecherche.getIdEtats(),
                StringValueTransformer.getInstance());
        bq.add((Query) getInQuery("etat.id", listeValeurs), BooleanClause.Occur.MUST);
    }
    // Critre sur la liste des agences
    if (criteresRecherche.getIdAgences() != null && !criteresRecherche.getIdAgences().isEmpty()) {
        final List<String> listeValeurs = (List<String>) CollectionUtils
                .collect(criteresRecherche.getIdAgences(), StringValueTransformer.getInstance());
        bq.add((Query) getInQuery("agence.id", listeValeurs), BooleanClause.Occur.MUST);
    }
    // Critre sur la liste des identifiants extrieurs des fonctions
    if (criteresRecherche.getListeIdsExtsFonctions() != null
            && !criteresRecherche.getListeIdsExtsFonctions().isEmpty()) {
        final List<String> listeValeurs = (List<String>) CollectionUtils
                .collect(criteresRecherche.getListeIdsExtsFonctions(), StringValueTransformer.getInstance());
        bq.add((Query) getInQuery("fonction.identifiantExterieur", listeValeurs), BooleanClause.Occur.SHOULD);
    }

    // PARAMETRE TOUJOURS VRAI POUR RECHERCHER SANS CRITERE
    if (criteresRecherche.getNom() == null || "".equals(criteresRecherche.getNom())) {
        final QueryParser parser = new QueryParser(getMatchingVersion(), FIELD_NOM,
                getAnalyser(PersonnePhysique.class));
        parser.setAllowLeadingWildcard(true);
        final org.apache.lucene.search.Query requeteLucene = parser.parse("*");
        bq.add(requeteLucene, BooleanClause.Occur.MUST);
    }

    // CONSTRUCTION DE LA REQUETE
    final FullTextQuery fullTextQuery = createFullTextQuery(bq, Ressource.class);

    // AJOUT DES INFORMATION DE TRI
    if (criteres.getListeSorts().size() > 0) {
        final SortField[] listeChamp = new SortField[criteres.getListeSorts().size()];
        for (int index = 0; index < criteres.getListeSorts().size(); index++) {
            listeChamp[index] = new SortField(criteres.getListeSorts().get(index).getSortField(),
                    SortField.STRING, criteres.getListeSorts().get(index)
                            .getSortAsc() == RemotePagingSort.REMOTE_PAGING_SORT_DESC);
        }
        final Sort sort = new Sort(listeChamp);
        fullTextQuery.setSort(sort);

    }

    // AJOUT DES INFORMATIONS DE PAGINATION
    fullTextQuery.setFirstResult(criteres.getFirstResult());
    fullTextQuery.setMaxResults(criteres.getMaxResult());

    // RETOURNE LA LISTE DES RESULTATS ET LE NOMBRE TOTAL DE RESULTAT (non affct par la pagination)
    return new ResultatPaginationFullText<Ressource>(fullTextQuery.list(), fullTextQuery.getResultSize());
}

From source file:com.stimulus.archiva.search.StandardSearch.java

License:Open Source License

protected Sort getSortPreference() {
    Sort sort;/*from   ww w  .ja v  a2 s  .  c  o  m*/
    String sortField = getSortField();
    SortOrder so = getSortOrder();
    boolean sortOrder;
    if (so == SortOrder.DESCENDING)
        sortOrder = true;
    else if (so == SortOrder.ASCENDING)
        sortOrder = false;
    else
        return null;

    Locale locale = new Locale(language);
    if (sortField.equals("size") || sortField.equals("priority"))
        sort = new Sort(new SortField[] { new SortField(sortField, SortField.FLOAT, sortOrder) });
    else if (sortField.equals("attach"))
        sort = new Sort(new SortField[] { new SortField(sortField, SortField.INT, !sortOrder) });
    else if (sortField.equals("score"))
        sort = new Sort(SortField.FIELD_SCORE);
    else if (sortField.equals("subject") || sortField.equals("to") || sortField.equals("from"))
        sort = new Sort(new SortField[] { new SortField(sortField + "s", sortOrder) });
    else if (sortField.equals("sentdate"))
        sort = new Sort(new SortField[] { new SortField(sortField, sortOrder) });
    else if (sortField.equals("archivedate"))
        sort = new Sort(new SortField[] { new SortField(sortField, sortOrder) });
    else if (sortField.equals("receiveddate"))
        sort = new Sort(new SortField[] { new SortField(sortField, sortOrder) });
    else
        return null;
    return sort;
}

From source file:com.stratio.cassandra.index.query.Sorting.java

License:Apache License

/**
 * Returns the Lucene's {@link Sort} representing this {@link Sorting}.
 *
 * @param schema The {@link Schema} to be used.
 * @return the Lucene's {@link Sort} representing this {@link Sorting}.
 *//*from w ww. ja va  2 s  . c  o  m*/
public Sort sort(Schema schema) {
    SortField[] sortFields = new SortField[sortingFields.size()];
    for (int i = 0; i < sortingFields.size(); i++) {
        sortFields[i] = sortingFields.get(i).sortField(schema);
    }
    return new Sort(sortFields);
}

From source file:com.stratio.cassandra.index.RowMapperSkinny.java

License:Apache License

/**
 * Returns the Lucene {@link Sort} to get {@link Document}s in the same order that is used in Cassandra.
 *
 * @return The Lucene {@link Sort} to get {@link Document}s in the same order that is used in Cassandra.
 *//*from   ww w.  j  a  va2 s.c o m*/
public Sort sort() {
    return new Sort(tokenMapper.sortFields());
}