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:org.apache.zeppelin.search.LuceneSearch.java

License:Apache License

@Override
public List<Map<String, String>> query(String queryStr) {
    if (null == directory) {
        throw new IllegalStateException("Something went wrong on instance creation time, index dir is null");
    }//from   w  w  w  . j  av a 2s.  c  o m
    List<Map<String, String>> result = Collections.emptyList();
    try (IndexReader indexReader = DirectoryReader.open(directory)) {
        IndexSearcher indexSearcher = new IndexSearcher(indexReader);
        Analyzer analyzer = new StandardAnalyzer();
        MultiFieldQueryParser parser = new MultiFieldQueryParser(
                new String[] { SEARCH_FIELD_TEXT, SEARCH_FIELD_TITLE }, analyzer);

        Query query = parser.parse(queryStr);
        logger.debug("Searching for: " + query.toString(SEARCH_FIELD_TEXT));

        SimpleHTMLFormatter htmlFormatter = new SimpleHTMLFormatter();
        Highlighter highlighter = new Highlighter(htmlFormatter, new QueryScorer(query));

        result = doSearch(indexSearcher, query, analyzer, highlighter);
    } catch (IOException e) {
        logger.error("Failed to open index dir {}, make sure indexing finished OK", directory, e);
    } catch (ParseException e) {
        logger.error("Failed to parse query " + queryStr, e);
    }
    return result;
}

From source file:org.apereo.portal.rest.search.PortletsSearchStrategy.java

License:Apache License

@PostConstruct
public void init() {
    final String[] fields = Arrays.stream(SearchField.values()).map(SearchField::getValue)
            .toArray(String[]::new);
    queryParser = new MultiFieldQueryParser(fields, new StandardAnalyzer());
}

From source file:org.carrot2.source.lucene.LuceneDocumentSource.java

License:Open Source License

/**
 * Fetch search engine response.//w  w w . j  av  a 2  s .c o  m
 */
protected SearchEngineResponse fetchSearchResponse() throws Exception {
    if (directory == null) {
        throw new ProcessingException("Directory attribute must not be empty.");
    }

    if (this.query instanceof String) {
        final String[] searchFields = fieldMapper.getSearchFields();
        if (searchFields == null || searchFields.length == 0) {
            throw new ProcessingException("At least one search field must be given for a plain text query. "
                    + "Alternatively, use a Lucene Query object.");
        }

        final String textQuery = (String) query;
        if (StringUtils.isEmpty(textQuery)) {
            throw new ProcessingException(
                    "An instantiated Lucene Query object or a non-empty " + "plain text query is required.");
        }

        if (searchFields.length == 1) {
            query = new QueryParser(searchFields[0], analyzer).parse(textQuery);
        } else {
            query = new MultiFieldQueryParser(searchFields, analyzer).parse(textQuery);
        }
    }

    final SearchEngineResponse response = new SearchEngineResponse();
    final IndexSearcher searcher = indexOpen(directory);
    final TopDocs docs = searcher.search((Query) query, results);

    response.metadata.put(SearchEngineResponse.RESULTS_TOTAL_KEY, docs.totalHits);

    for (ScoreDoc scoreDoc : docs.scoreDocs) {
        final Document doc = new Document();
        final org.apache.lucene.document.Document luceneDoc = searcher.doc(scoreDoc.doc);

        // Set score before mapping to give the mapper a chance to override it
        doc.setScore((double) scoreDoc.score);

        if (keepLuceneDocuments) {
            doc.setField(LUCENE_DOCUMENT_FIELD, luceneDoc);
            doc.addSerializationListener(removeLuceneDocument);
        }

        this.fieldMapper.map((Query) query, analyzer, luceneDoc, doc);
        response.results.add(doc);
    }

    return response;
}

From source file:org.eclipse.agail.recommenderserver.RecommendCloud.java

License:Open Source License

public void generateQuery(GatewayProfile profile) {

    String[] fields = { "locations", "pricing", "services", "runtimes" };
    String loc = "EU";
    String price = "free";
    String services = "TODO_ADD_MORE";

    if (profile.getLocation() != "")
        loc = profile.getLocation();//from w  ww.j a v  a  2s.  c  om

    if (profile.getPricingPreferences() != "")
        price = profile.getPricingPreferences().replaceAll(",", " OR ");

    if (profile.getLocation() != "")
        loc = profile.getLocation();

    if (profile.getRequiredServices() != "")
        services = profile.getRequiredServices().replaceAll(",", " OR ");

    String[] queries = { loc, price, services, "node" };

    BooleanClause.Occur[] flags = { BooleanClause.Occur.MUST, BooleanClause.Occur.SHOULD,
            BooleanClause.Occur.MUST, BooleanClause.Occur.MUST };

    MultiFieldQueryParser queryParserCloud = new MultiFieldQueryParser(queries,
            CloudMarketplace.analyzer_cloud);

    try {
        finalQuery = queryParserCloud.parse(queries, fields, flags, CloudMarketplace.analyzer_cloud);
    } catch (org.apache.lucene.queryparser.classic.ParseException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
}

From source file:org.encuestame.persistence.dao.imp.AbstractHibernateDaoSupport.java

License:Apache License

/**
 * Fetch by multi query parser full text.
 * @param keyword keyword to search/*from  w  w w . j  a va2s  .co m*/
 * @param fields list of fields.
 * @param clazz class referece
 * @param criteria {@link Criteria} reference.
 * @param analyzer {@link Analyzer} reference.
 * @return list of results.
 */
public List<?> fetchMultiFieldQueryParserFullText(final String keyword, final String[] fields,
        final Class<?> clazz, final Criteria criteria, final Analyzer analyzer) {
    final MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, analyzer);
    Query query = null;
    try {
        query = parser.parse(keyword);
    } catch (ParseException e) {
        log.error("Error on Parse Query " + e);
    }
    return fetchFullTextSession(clazz, criteria, analyzer, query);
}

From source file:org.hibernate.search.test.event.autoindexembeddable.EventBasedEmbeddableCollectionUpdateTest.java

License:LGPL

@SuppressWarnings("unchecked")
private List<Book> search(String searchQuery) throws ParseException {
    QueryParser parser = new MultiFieldQueryParser(new String[] {}, new StandardAnalyzer());
    FullTextQuery query = Search.getFullTextEntityManager(entityManager)
            .createFullTextQuery(parser.parse(searchQuery), Book.class);
    return (List<Book>) query.getResultList();
}

From source file:org.lukhnos.lucenestudy.Indexer.java

License:MIT License

public static Query parseQuery(Analyzer analyzer, String queryStr) throws ParseException {
    String[] fields = { Indexer.TITLE_FIELD_NAME, Indexer.REVIEW_FIELD_NAME };
    QueryParser parser = new MultiFieldQueryParser(fields, analyzer);
    return parser.parse(queryStr);
}

From source file:org.pageseeder.flint.lucene.query.Predicate.java

License:Apache License

/**
 * Computes the query for this question.
 *
 * <p>This only needs to be done once.
 *
 * @param analyzer The analyser used by the underlying index.
 *
 * @throws ParseException If the question could not be parsed properly.
 *//*from   ww  w . j  a va2  s  . c o  m*/
private void compute(Analyzer analyzer) throws ParseException {
    String[] fields = this._fields.keySet().toArray(new String[] {});
    MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, analyzer);
    this._query = parser.parse(this._predicate);
}

From source file:org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.help.HelpManager.java

public String giveHelp(String[] words) {
    //TODO Add here for example credits, copyright, license

    if (words.length <= 1) {
        IntroHelp.print(stdout);//from  w w  w.  java 2 s .co  m
        return "";
    }

    if (!indexAvailable()) {
        return "";
    }

    Analyzer multiFieldAnalyzer = Onthology.multiFieldAnalyzer();

    try {
        String searchFields[] = { "index", "synopsis", "doc" };

        QueryParser parser = new MultiFieldQueryParser(searchFields, multiFieldAnalyzer);

        StringBuilder sb = new StringBuilder();
        for (int i = 1; i < words.length; i++) {
            sb.append(" ").append(escapeForQuery(words[i]));
        }
        Query query;
        try {
            query = parser.parse(sb.toString());
        } catch (ParseException e) {
            stderr.println("Cannot parse query: " + sb + ", " + e.getMessage());
            return "";
        }

        if (words[0].equals("help")) {
            return reportHelp(words, indexSearcher.search(query, maxSearch).scoreDocs);
        } else {
            return reportApropos(words, indexSearcher.search(query, maxSearch).scoreDocs);
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return "";
}

From source file:org.tightblog.service.indexer.SearchTask.java

License:Apache License

@Override
public void doRun() {
    final int docLimit = 500;
    searchResults = null;/*  ww w  .j  a  va2 s. co  m*/
    searcher = null;

    try (Analyzer analyzer = manager.getAnalyzer()) {
        if (analyzer != null) {
            IndexReader reader = manager.getDirectoryReader();
            if (searcher == null) {
                searcher = new IndexSearcher(reader);
            }

            MultiFieldQueryParser multiParser = new MultiFieldQueryParser(SEARCH_FIELDS, analyzer);

            // Make it an AND by default. Comment this out for an or (default)
            multiParser.setDefaultOperator(MultiFieldQueryParser.Operator.AND);

            // Create a query object out of our term
            Query query = multiParser.parse(term);

            Term tUsername = getTerm(FieldConstants.WEBLOG_HANDLE, weblogHandle);

            if (tUsername != null) {
                query = new BooleanQuery.Builder().add(query, BooleanClause.Occur.MUST)
                        .add(new TermQuery(tUsername), BooleanClause.Occur.MUST).build();
            }

            if (category != null) {
                Term tCategory = new Term(FieldConstants.CATEGORY, category.toLowerCase());
                query = new BooleanQuery.Builder().add(query, BooleanClause.Occur.MUST)
                        .add(new TermQuery(tCategory), BooleanClause.Occur.MUST).build();
            }

            searchResults = searcher.search(query, docLimit, SORTER);
        }
    } catch (IOException | ParseException e) {
        LOG.error("Error searching index", e);
    }
}