本文整理汇总了Java中org.apache.lucene.queryparser.classic.MultiFieldQueryParser类的典型用法代码示例。如果您正苦于以下问题:Java MultiFieldQueryParser类的具体用法?Java MultiFieldQueryParser怎么用?Java MultiFieldQueryParser使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
MultiFieldQueryParser类属于org.apache.lucene.queryparser.classic包,在下文中一共展示了MultiFieldQueryParser类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: search
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser; //导入依赖的package包/类
/**
* 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
* @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();
}
示例2: findPosts
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser; //导入依赖的package包/类
private List<Post> findPosts() {
try {
FullTextSession fullTextSession = getFullTextSession((Session) entityManager.getDelegate());
Builder builder = new Builder();
String[] fields = new String[] { "message.text", "topic.subject" };
MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, new StandardAnalyzer());
builder.add(parser.parse(POST_TEXT), MUST);
builder.add(new TermQuery(new Term("topic.forum.id", "0")), MUST);
builder.add(new TermQuery(new Term("topic.forum.category.id", "0")), MUST);
builder.add(new WildcardQuery(new Term("poster.userId", "root")), MUST);
addPostTimeQuery(builder);
FullTextQuery fullTextQuery = fullTextSession.createFullTextQuery(builder.build(), Post.class);
fullTextQuery.setSort(getSort());
fullTextQuery.setFirstResult(0);
fullTextQuery.setMaxResults(15);
@SuppressWarnings("unchecked")
List<Post> posts = fullTextQuery.list();
return posts;
} catch (ParseException e) {
logger.severe("error");
return null;
}
}
开发者ID:PacktPublishing,项目名称:Mastering-Java-EE-Development-with-WildFly,代码行数:24,代码来源:SearchTestCase.java
示例3: initialize
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser; //导入依赖的package包/类
@Override
public void initialize(UimaContext context) throws ResourceInitializationException {
super.initialize(context);
hits = UimaContextHelper.getConfigParameterIntValue(context, "hits", 100);
// query constructor
constructor = UimaContextHelper.createObjectFromConfigParameter(context,
"query-string-constructor", "query-string-constructor-params",
BooleanBagOfPhraseQueryStringConstructor.class, QueryStringConstructor.class);
// lucene
Analyzer analyzer = UimaContextHelper.createObjectFromConfigParameter(context, "query-analyzer",
"query-analyzer-params", StandardAnalyzer.class, Analyzer.class);
String[] fields = UimaContextHelper.getConfigParameterStringArrayValue(context, "fields");
parser = new MultiFieldQueryParser(fields, analyzer);
String index = UimaContextHelper.getConfigParameterStringValue(context, "index");
try {
reader = DirectoryReader.open(FSDirectory.open(Paths.get(index)));
} catch (IOException e) {
throw new ResourceInitializationException(e);
}
searcher = new IndexSearcher(reader);
idFieldName = UimaContextHelper.getConfigParameterStringValue(context, "id-field", null);
titleFieldName = UimaContextHelper.getConfigParameterStringValue(context, "title-field", null);
textFieldName = UimaContextHelper.getConfigParameterStringValue(context, "text-field", null);
uriPrefix = UimaContextHelper.getConfigParameterStringValue(context, "uri-prefix", null);
}
示例4: search
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser; //导入依赖的package包/类
public synchronized ObjectMatrix2D search(String searchString) {
try {
MultiFieldQueryParser p = new MultiFieldQueryParser(Version.LUCENE_47, new String[] { VALUESTRING },
getAnalyzer());
Query query = p.parse(searchString);
TopDocs docs = getIndexSearcher().search(query, 100);
ObjectMatrix2D result = ObjectMatrix2D.Factory.zeros(docs.totalHits, 3);
for (int row = 0; row < docs.totalHits; row++) {
ScoreDoc match = docs.scoreDocs[row];
Document doc = getIndexSearcher().doc(match.doc);
result.setAsFloat(match.score, row, 0);
result.setAsObject(SerializationUtil.deserialize(doc.getBinaryValue(KEYDATA).bytes), row, 1);
result.setAsObject(SerializationUtil.deserialize(doc.getBinaryValue(VALUEDATA).bytes), row, 2);
}
return result;
} catch (Exception e) {
throw new RuntimeException("could not search documents: " + searchString, e);
}
}
示例5: simConsqQuery
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser; //导入依赖的package包/类
private Query simConsqQuery(String cons, String consVal, double sim) {
String[] field = new String[] { cons };
MultiFieldQueryParser parser = new MultiFieldQueryParser(
org.apache.lucene.util.Version.LUCENE_48, field,
new StandardAnalyzer(org.apache.lucene.util.Version.LUCENE_48));
if (consVal == null || "".equals(consVal.trim())) {
consVal = "\" \"";
}
Query q = null;
try {
q = parser.parse(QueryParser.escape(consVal + "~ "
+ (int) ((1.0d - sim) * (consVal.length()))));
} catch (ParseException e) {
logger.log(ProdLevel.PROD, "EXCEPTION : " + e.getMessage());
}
// logger.log(ProdLevel.PROD, "Executing lucene query : " + q);
return q;
}
示例6: buildApproxMatchingQuery
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser; //导入依赖的package包/类
public Query buildApproxMatchingQuery(String colsStr, List<String> cols) {
StringBuilder sb = new StringBuilder();
sb.append(colsStr);
sb.append("~");
MultiFieldQueryParser parser = new MultiFieldQueryParser(
org.apache.lucene.util.Version.LUCENE_48,
cols.toArray(new String[cols.size()]), new StandardAnalyzer(
org.apache.lucene.util.Version.LUCENE_48));
Query q = null;
try {
q = parser.parse(QueryParser.escape(sb.toString()));
// logger.log(DebugLevel.DEBUG, "Approx data matching query : " +
// q);
} catch (ParseException e) {
logger.log(ProdLevel.PROD, "EXCEPTION : " + e.getMessage());
}
return q;
}
示例7: getQueryParser
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser; //导入依赖的package包/类
private MultiFieldQueryParser getQueryParser() {
MultiFieldQueryParser queryParser = new MultiFieldQueryParser(getAllDefaultSearchableFields(), analyzer) {
@Override
protected Query getRangeQuery(String field, String part1, String part2, boolean startInclusive,
boolean endInclusive) throws ParseException {
if (field != null && getIndex(field).numeric) {
Long min = getWithDefault(part1, null);
Long max = getWithDefault(part2, null);
return NumericRangeQuery.newLongRange(field, min, max, true, true);
} else if (field != null) {
return new TermQuery(new Term(field));
}
return super.getRangeQuery(null, part1, part2, startInclusive, endInclusive);
}
};
queryParser.setDefaultOperator(QueryParser.Operator.AND);
queryParser.setLocale(LOCALE);
queryParser.setAnalyzeRangeTerms(true);
queryParser.setLowercaseExpandedTerms(true);
return queryParser;
}
示例8: qs
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser; //导入依赖的package包/类
/**
* Tries to parse a query string in order to check if it is valid.
* @param query a Lucene query string
* @return the query if valid, or '*' if invalid
*/
static Query qs(String query, Collection<String> fields) {
if (fields == null || fields.isEmpty()) {
fields = Collections.singletonList(Config._NAME);
}
if (StringUtils.isBlank(query)) {
query = "*";
}
MultiFieldQueryParser parser = new MultiFieldQueryParser(fields.toArray(new String[0]), new StandardAnalyzer());
parser.setAllowLeadingWildcard(false);
//parser.setLowercaseExpandedTerms(false); // DEPRECATED in Lucene 7.x
query = query.trim();
if (query.length() > 1 && query.startsWith("*")) {
query = query.substring(1);
}
if (!StringUtils.isBlank(query) && !"*".equals(query)) {
try {
Query q = parser.parse(query);
return q;
} catch (Exception ex) {
logger.warn("Failed to parse query string '{}'.", query);
}
}
return new MatchAllDocsQuery();
}
示例9: search
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser; //导入依赖的package包/类
public Set<String> search(String q) throws IOException {
Set<String> recipes = new LinkedHashSet<>();
String fields[] = new String[]{"description", "steps"};
logger.debug(String.format("searching for %s", q));
try (IndexReader reader = DirectoryReader.open(index)) {
int hitsPerPage = 1000;
IndexSearcher searcher = new IndexSearcher(reader);
Query query = new MultiFieldQueryParser(fields, analyzer).parse(q);
TopScoreDocCollector collector = TopScoreDocCollector.create(hitsPerPage, null);
searcher.search(query, collector);
ScoreDoc[] hits = collector.topDocs().scoreDocs;
for (ScoreDoc hit : hits) {
Document d = searcher.doc(hit.doc);
recipes.add(d.get("title"));
}
} catch (CorruptIndexException | ParseException e) {
logger.error(e);
}
logger.debug(String.format("found %d results", recipes.size()));
return recipes;
}
示例10: searchPage
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser; //导入依赖的package包/类
@RequestMapping(value = "/search", method = RequestMethod.GET)
public String searchPage(
Model model,
@RequestParam(value = "keyword", required = false) String keyword) {
String[] fieldList = {"uid", "rpcid", "traceid", "rt_type", "url", "param", "ip", "httpcod", "project"};
Map<String, Float> boosts = new HashMap<>();
boosts.put("uid", 1.0f);
boosts.put("ip", 1.0f);
boosts.put("rpcid", 1.0f);
boosts.put("traceid", 1.0f);
boosts.put("rt_type", 1.0f);
boosts.put("url", 1.0f);
boosts.put("urlraw", 1.0f);
boosts.put("param", 1.0f);
boosts.put("httpcode", 1.0f);
boosts.put("project", 1.0f);
MultiFieldQueryParser mulFieldQueryParser = new MultiFieldQueryParser(fieldList, new StandardAnalyzer(), boosts);
Query query;
try {
query = mulFieldQueryParser.parse(keyword);
} catch (Exception e) {
model.addAttribute("msg", "query parser error");
return "search";
}
Sort sort = new Sort(new SortField("time", SortField.Type.DOUBLE, true));
ResponseJson result = indexHelper.searchByQuery(DateTimeHelper.getCurrentTime(), query, 0, 1000, sort);
model.addAttribute("resultlist", result.getResult());
model.addAttribute("keyword", keyword);
return "search";
}
示例11: string
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser; //导入依赖的package包/类
protected void string(StringQuery<T> stringQuery) {
try {
String[] fields = stringQuery.getFields();
IndexedTypeIdentifier iti = getIndexedTypeIdentifier(stringQuery.getEntityClass());
Analyzer analyzer = getSearchIntegrator().getAnalyzer(iti);
QueryParser parser = new MultiFieldQueryParser(fields, analyzer);
Query luceneQuery = parser.parse(stringQuery.getQuery());
fillQuery(stringQuery, luceneQuery);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
示例12: createLuceneQuery
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser; //导入依赖的package包/类
private org.apache.lucene.search.Query createLuceneQuery(String query) {
try {
return MultiFieldQueryParser.parse(
new String[] {query},
new String[] {field},
analyzer);
} catch (ParseException e) {
throw new QueryException("Cannot parse query", e);
}
}
示例13: runQuery
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser; //导入依赖的package包/类
/**
* Performs scoring on the query provided.
* @param qno
* @param queryTerms
* @return
*/
public ScoreDoc[] runQuery(String qno, String queryTerms){
ScoreDoc[] hits = null;
String[] fields = new String[fl.fields.size()];
Map<String, Float> boosts = new HashMap<>();
int i = 0;
for (Field f : fl.fields) {
fields[i] = f.fieldName;
boosts.put(f.fieldName, f.fieldBoost);
i++;
}
try {
MultiFieldQueryParser mfq = new MultiFieldQueryParser(fields, analyzer, boosts);
Query q = mfq.parse(queryTerms);
System.out.println(qno+ ": " + q.toString());
try {
TopDocs results = searcher.search(q, p.maxResults);
hits = results.scoreDocs;
} catch (IOException ioe) {
System.out.println(" caught a " + ioe.getClass() +
"\n with message: " + ioe.getMessage());
}
} catch (ParseException pe){
System.out.println("Can't parse query");
}
return hits;
}
示例14: getQueryParser
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser; //导入依赖的package包/类
private MultiFieldQueryParser getQueryParser(final Analyzer analyzer) {
final Map<String, Float> boosts = new HashMap<String, Float>();
boosts.put("title", 2.5F);
boosts.put("description", 2F);
boosts.put("owner.name", 1.5F);
boosts.put("owner.username", 1.3F);
return new MultiFieldQueryParser(LuceneUtils.LUCENE_VERSION, FIELDS_FULL_TEXT, analyzer, boosts);
}
示例15: getQueryParser
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser; //导入依赖的package包/类
private MultiFieldQueryParser getQueryParser(final Analyzer analyzer) {
final Map<String, Float> boosts = new HashMap<String, Float>();
boosts.put("customValues", 2F);
boosts.put("by.name", 0.5F);
boosts.put("by.username", 0.5F);
return new MultiFieldQueryParser(LuceneUtils.LUCENE_VERSION, FIELDS_FULL_TEXT, analyzer, boosts);
}