Example usage for org.apache.lucene.queryparser.classic MultiFieldQueryParser MultiFieldQueryParser

List of usage examples for org.apache.lucene.queryparser.classic MultiFieldQueryParser MultiFieldQueryParser

Introduction

In this page you can find the example usage for org.apache.lucene.queryparser.classic MultiFieldQueryParser MultiFieldQueryParser.

Prototype

public MultiFieldQueryParser(String[] fields, Analyzer analyzer) 

Source Link

Document

Creates a MultiFieldQueryParser.

Usage

From source file:br.ufba.dcc.mestrado.computacao.repository.impl.ProjectRepositoryImpl.java

public FullTextQuery findAllByFullTextQuery(String query) {

    FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(getEntityManager());

    Analyzer analyzer = fullTextEntityManager.getSearchFactory().getAnalyzer(getEntityClass());

    String[] searchFields = { SearchFieldsEnum.projectName.fieldName(),
            SearchFieldsEnum.projectDescription.fieldName(), SearchFieldsEnum.tagName.fieldName() };

    MultiFieldQueryParser queryParser = new MultiFieldQueryParser(searchFields, analyzer);

    /*org.apache.lucene.queryParser.MultiFieldQueryParser queryParser =
    new MultiFieldQueryParser(/*w ww .  j  a v a2 s .c  o m*/
          Version.LUCENE_36, 
          searchFields, 
          analyzer);*/

    FullTextQuery fullTextQuery = null;

    try {

        org.apache.lucene.search.Query luceneQuery = queryParser.parse(query);

        fullTextQuery = fullTextEntityManager.createFullTextQuery(luceneQuery, OpenHubProjectEntity.class);

        configureRelevanceSort(fullTextQuery);

    } catch (EmptyQueryException | ParseException ex) {

    }

    return fullTextQuery;
}

From source file:bzh.terrevirtuelle.navisu.gazetteer.impl.lucene.GeoNameResolver.java

License:Apache License

private HashMap<String, List<Location>> resolveEntities(List<String> locationNames, int count,
        IndexReader reader) throws IOException {
    if (locationNames.size() >= 200) {
        hitsPerPage = 5; // avoid heavy computation
    }//w  w w . j ava  2 s .c o m
    IndexSearcher searcher = new IndexSearcher(reader);
    Query q = null;

    HashMap<String, List<Location>> allCandidates = new HashMap<String, List<Location>>();

    for (String name : locationNames) {

        if (!allCandidates.containsKey(name)) {
            try {
                //query is wrapped in additional quotes (") to avoid query tokenization on space
                q = new MultiFieldQueryParser(new String[] { FIELD_NAME_NAME, FIELD_NAME_ALTERNATE_NAMES },
                        analyzer).parse(String.format("\"%s\"", name));

                Sort sort = new Sort(populationSort);
                //Fetch 3 times desired values, these will be sorted on code and only desired number will be kept
                ScoreDoc[] hits = searcher.search(q, hitsPerPage * 3, sort).scoreDocs;

                getMatchingCandidates(searcher, allCandidates, name, hits);
            } catch (org.apache.lucene.queryparser.classic.ParseException e) {
                e.printStackTrace();
            }
        }
    }

    HashMap<String, List<Location>> resolvedEntities = new HashMap<String, List<Location>>();
    pickBestCandidates(resolvedEntities, allCandidates, count);
    return resolvedEntities;
}

From source file:ch.algotrader.rest.index.SecurityIndexer.java

License:Open Source License

public List<SecurityVO> search(String queryStr) throws ParseException {
    try (IndexReader reader = DirectoryReader.open(index)) {
        IndexSearcher searcher = new IndexSearcher(reader);
        QueryParser queryParser = new MultiFieldQueryParser(FIELDS, new StandardAnalyzer());
        queryParser.setAllowLeadingWildcard(true);
        Query query = queryParser.parse(queryStr);

        TopDocs results = searcher.search(query, 10);
        return Arrays.asList(results.scoreDocs).stream().map(sd -> searchDocument(searcher, sd))
                .mapToLong(d -> d.getField("id").numericValue().longValue()).mapToObj(securityCache::get)
                .collect(Collectors.toList());

    } catch (IOException ioe) {
        throw new UnrecoverableCoreException("Unexpected I/O error accessing security index", ioe);
    }// w  ww  .  j av  a  2s  . c om
}

From source file:com.amalto.core.storage.hibernate.LuceneQueryGenerator.java

License:Open Source License

private Query parseQuery(String[] fieldsAsArray, String fullTextQuery, String keywords) {
    MultiFieldQueryParser parser = new MultiFieldQueryParser(fieldsAsArray, new StandardAnalyzer());
    // Very important! Lucene does an implicit lower case for "expanded terms" (which is something used).
    parser.setLowercaseExpandedTerms(true);
    try {//from  w ww. ja  v a  2 s.c  o m
        return parser.parse(fullTextQuery);
    } catch (Exception e) {
        if (org.apache.lucene.queryparser.classic.ParseException.class.isInstance(e)) {
            throw new UnsupportedFullTextQueryException("'" + keywords + "' is unsupported keywords", e); //$NON-NLS-1$ //$NON-NLS-2$
        }
        throw new RuntimeException("Invalid generated Lucene query", e); //$NON-NLS-1$
    }
}

From source file:com.gemstone.gemfire.cache.lucene.internal.StringQueryProvider.java

License:Apache License

@Override
public synchronized Query getQuery(LuceneIndex index) throws QueryException {
    if (luceneQuery == null) {
        String[] fields = index.getFieldNames();

        //TODO  get the analyzer from the index
        MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, new StandardAnalyzer());
        try {/*from  w ww  .  j  av a  2 s  .c  o m*/
            luceneQuery = parser.parse(query);
        } catch (ParseException e) {
            logger.debug("Malformed lucene query: " + query, e);
            throw new QueryException(e);
        }
    }
    return luceneQuery;
}

From source file:com.github.wxiaoqi.search.lucene.util.QueryUtil.java

License:Open Source License

public static Query query(String query, Analyzer analyzer, String... fields) throws ParseException {
    BooleanQuery.setMaxClauseCount(32768);
    query = queryStringFilter(query); /*?*/
    MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, analyzer);
    parser.setDefaultOperator(QueryParser.Operator.OR);
    return parser.parse(query);
}

From source file:com.nestedbird.modules.entitysearch.EntitySearch.java

License:Open Source License

/**
 * Searches the lucene store for a specific query
 *
 * @param <T>       What type of information are we searching
 * @param clazz     The class of the information we are searching
 * @param queryText The query text/*from w  w  w. j a  va2 s  .c  o  m*/
 * @return list of entities
 * @throws ParseException the parse exception
 */
public final <T extends BaseEntity> List<Object[]> search(final Class<T> clazz, final String queryText)
        throws ParseException {
    final FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);

    final SearchFactory searchFactory = fullTextEntityManager.getSearchFactory();

    final QueryParser parser = new MultiFieldQueryParser(getClassLuceneFields(clazz),
            searchFactory.getAnalyzer(clazz));

    final List<Query> parsedQueries = Arrays.stream(queryText.split("AND")).map(e -> parseQuery(e, parser))
            .filter(Objects::nonNull).collect(Collectors.toList());

    final BooleanQuery.Builder bq = new BooleanQuery.Builder();
    parsedQueries.forEach(e -> bq.add(e, BooleanClause.Occur.MUST));

    final FullTextQuery jpaQuery = fullTextEntityManager.createFullTextQuery(bq.build(), clazz);
    jpaQuery.setProjection(ProjectionConstants.SCORE, ProjectionConstants.EXPLANATION,
            ProjectionConstants.THIS);

    return (List<Object[]>) jpaQuery.getResultList();
}

From source file:com.orientechnologies.lucene.builder.OQueryBuilderImpl.java

License:Apache License

protected Query getQueryParser(OIndexDefinition index, String key, Analyzer analyzer) throws ParseException {
    QueryParser queryParser;/*  w  w w .jav a  2 s.  c o m*/
    if ((key).startsWith("(")) {
        queryParser = new QueryParser("", analyzer);

    } else {
        String[] fields = null;
        if (index.isAutomatic()) {
            fields = index.getFields().toArray(new String[index.getFields().size()]);
        } else {
            int length = index.getTypes().length;

            fields = new String[length];
            for (int i = 0; i < length; i++) {
                fields[i] = "k" + i;
            }
        }

        queryParser = new MultiFieldQueryParser(fields, analyzer);
    }

    queryParser.setAllowLeadingWildcard(allowLeadingWildcard);

    queryParser.setLowercaseExpandedTerms(lowercaseExpandedTerms);

    try {
        return queryParser.parse(key);

    } catch (org.apache.lucene.queryparser.classic.ParseException e) {
        throw new ParseException(e.getMessage());
    }

}

From source file:com.semantic.swing.facet.SearchPanel.java

@Override
public Query createQuery() {
    BooleanQuery.Builder ret = null;//from  ww w . j av  a 2s  .co m
    /* generate query - AND phrase query */
    StringBuilder buffer = new StringBuilder();
    for (int i = 0, size = listModel.getSize(); i < size; i++) {
        buffer.append("\"");
        buffer.append(listModel.getElementAt(i).getSuggestion());
        buffer.append("\"");
        if (i + 1 < size) {
            buffer.append(" AND ");
        }
    }
    /* */
    if (buffer.length() > 0) {
        /* need take care very much about analyzer */
        MultiFieldQueryParser parser = new MultiFieldQueryParser(
                new String[] { ContentField.NAME, "dc:creator", "dc:title" }, new StandardAnalyzer());
        /* standard analyzed */
        try {
            ret = new BooleanQuery.Builder();
            ret.add(parser.parse(buffer.toString()), BooleanClause.Occur.FILTER);
        } catch (ParseException ex) {
            Logger.getLogger(SearchPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return ret != null ? ret.build() : null;
}

From source file:control.Search.java

/**
 * Search for previously indexed feeds through 'title' and 'description' fields, according to a query
 * /*w  ww  . j a  v  a 2 s . c  o  m*/
 * @param query terms to be considered in the search
 * @return a JSON representation of the retrieved feeds
 * @throws ParseException query parsing failure
 * @throws IOException  I/O issue when creating index
 */
public String queryIndexedFeeds(String query) throws ParseException, IOException {
    //creates IndexReader with analyzers
    IndexReader reader = DirectoryReader.open(index);
    IndexSearcher searcher = new IndexSearcher(reader);
    StandardAnalyzer analyzer = new StandardAnalyzer();
    MultiFieldQueryParser queryParser = new MultiFieldQueryParser(new String[] { "title", "description" },
            analyzer);

    //search for documents
    TopDocs docs = searcher.search(queryParser.parse(query), 25);
    ScoreDoc[] hits = docs.scoreDocs;

    //iterate over results and put on JSON format
    JSONArray jsonArray = new JSONArray();
    for (int i = 0; i < hits.length; i++) {
        int docId = hits[i].doc;
        Document d = searcher.doc(docId);

        //create new json object
        JSONObject json = new JSONObject();
        json.put("id", d.get("id"));
        json.put("link", d.get("link"));
        json.put("title", d.get("title"));
        json.put("description", d.get("description"));

        jsonArray.put(json);
    }

    reader.close();
    String ret = jsonArray.toString();

    return ret;
}