Here are the examples of the java api class org.apache.lucene.search.Query taken from open source projects.
1. MultiMatchQueryTests#testBlendNoTermQuery()
Project: elasticsearch
File: MultiMatchQueryTests.java
File: MultiMatchQueryTests.java
public void testBlendNoTermQuery() { FakeFieldType ft1 = new FakeFieldType(); ft1.setName("foo"); FakeFieldType ft2 = new FakeFieldType() { @Override public Query termQuery(Object value, QueryShardContext context) { return new MatchAllDocsQuery(); } }; ft2.setName("bar"); Term[] terms = new Term[] { new Term("foo", "baz") }; float[] boosts = new float[] { 2 }; Query expectedClause1 = BlendedTermQuery.booleanBlendedQuery(terms, boosts, false); Query expectedClause2 = new BoostQuery(new MatchAllDocsQuery(), 3); Query expected = new BooleanQuery.Builder().setDisableCoord(true).add(expectedClause1, Occur.SHOULD).add(expectedClause2, Occur.SHOULD).build(); Query actual = MultiMatchQuery.blendTerm(new BytesRef("baz"), null, 1f, new FieldAndFieldType(ft1, 2), new FieldAndFieldType(ft2, 3)); assertEquals(expected, actual); }
2. TestValueSourceCache#tryQuerySameTypes()
Project: lucene-solr
File: TestValueSourceCache.java
File: TestValueSourceCache.java
// This test should will fail because q1 and q3 evaluate as equal unless // fixes for bug 2829 are in place. void tryQuerySameTypes(String template, String numbers, String type) throws SyntaxError { String s1 = template; String s2 = template; String s3 = template; String[] numParts = numbers.split(","); String type2 = type.replace("val1", "val2"); for (int idx = 0; s1.contains("#"); ++idx) { String patV = "#v" + Integer.toString(idx); String patN = "#n" + Integer.toString(idx); s1 = s1.replace(patV, type).replace(patN, numParts[idx]); s2 = s2.replace(patV, type).replace(patN, numParts[idx]); s3 = s3.replace(patV, type2).replace(patN, numParts[idx]); } //SolrQueryRequest req1 = req( "q","*:*", "fq", s1); Query q1 = getQuery(s1); Query q2 = getQuery(s2); Query q3 = getQuery(s3); QueryUtils.checkEqual(q1, q2); QueryUtils.checkUnequal(q1, q3); }
3. QueryResultKeyTest#testFiltersOutOfOrder2()
Project: lucene-solr
File: QueryResultKeyTest.java
File: QueryResultKeyTest.java
@Test public void testFiltersOutOfOrder2() { Query fq1 = new TermQuery(new Term("test1", "field1")); Query fq2 = new TermQuery(new Term("test2", "field2")); Query query = new TermQuery(new Term("test3", "field3")); List<Query> filters = Arrays.asList(fq1, fq2); QueryResultKey key = new QueryResultKey(query, filters, null, 0); List<Query> newFilters = Arrays.asList(fq2, fq1); QueryResultKey newKey = new QueryResultKey(query, newFilters, null, 0); assertKeyEquals(key, newKey); }
4. TestQueryParser#testCJKSynonymsAND2()
Project: lucene-solr
File: TestQueryParser.java
File: TestQueryParser.java
/** more complex synonyms with default AND operator */ public void testCJKSynonymsAND2() throws Exception { BooleanQuery.Builder expectedB = new BooleanQuery.Builder(); expectedB.add(new TermQuery(new Term(FIELD, "?")), BooleanClause.Occur.MUST); Query inner = new SynonymQuery(new Term(FIELD, "?"), new Term(FIELD, "?")); expectedB.add(inner, BooleanClause.Occur.MUST); Query inner2 = new SynonymQuery(new Term(FIELD, "?"), new Term(FIELD, "?")); expectedB.add(inner2, BooleanClause.Occur.MUST); Query expected = expectedB.build(); QueryParser qp = new QueryParser(FIELD, new MockCJKSynonymAnalyzer()); qp.setDefaultOperator(Operator.AND); assertEquals(expected, qp.parse("???")); expected = new BoostQuery(expected, 2f); assertEquals(expected, qp.parse("???^2")); }
5. BoostingQueryBuilder#getQuery()
Project: lucene-solr
File: BoostingQueryBuilder.java
File: BoostingQueryBuilder.java
@Override public Query getQuery(Element e) throws ParserException { Element mainQueryElem = DOMUtils.getChildByTagOrFail(e, "Query"); mainQueryElem = DOMUtils.getFirstChildOrFail(mainQueryElem); Query mainQuery = factory.getQuery(mainQueryElem); Element boostQueryElem = DOMUtils.getChildByTagOrFail(e, "BoostQuery"); float boost = DOMUtils.getAttribute(boostQueryElem, "boost", DEFAULT_BOOST); boostQueryElem = DOMUtils.getFirstChildOrFail(boostQueryElem); Query boostQuery = factory.getQuery(boostQueryElem); Query bq = new BoostingQuery(mainQuery, boostQuery, boost); boost = DOMUtils.getAttribute(e, "boost", 1.0f); if (boost != 1f) { return new BoostQuery(bq, boost); } return bq; }
6. TestBooleanQuery#testReqExclCell()
Project: SIREn
File: TestBooleanQuery.java
File: TestBooleanQuery.java
@Test public void testReqExclCell() throws CorruptIndexException, IOException { for (int i = 0; i < 10; i++) { this.addDocument("<subj> <aaa> <bbb> . <subj> <ccc> <ddd> . <subj> <eee> <fff> . "); this.addDocument("<subj> <aaa> <bbb> . <subj> <ccc> <ddd> . <subj> <eee> <ggg> . "); } final Query nested1 = nbq(must("aaa")).bound(1, 1).getLuceneProxyQuery(); final Query nested2 = nbq(must("bbb")).bound(2, 2).getLuceneProxyQuery(); final Query nested3 = nbq(must("ggg")).bound(2, 2).getLuceneProxyQuery(); final BooleanQuery q = new BooleanQuery(); q.add(nested3, Occur.MUST_NOT); q.add(nested1, Occur.MUST); q.add(nested2, Occur.MUST); assertEquals(10, searcher.search(q, 10).totalHits); }
7. PercolatorService#queryBasedPercolating()
Project: elassandra
File: PercolatorService.java
File: PercolatorService.java
private void queryBasedPercolating(Engine.Searcher percolatorSearcher, PercolateContext context, QueryCollector percolateCollector) throws IOException { Query percolatorTypeFilter = context.indexService().mapperService().documentMapper(TYPE_NAME).typeFilter(); final Query filter; if (context.aliasFilter() != null) { BooleanQuery.Builder booleanFilter = new BooleanQuery.Builder(); booleanFilter.add(context.aliasFilter(), BooleanClause.Occur.MUST); booleanFilter.add(percolatorTypeFilter, BooleanClause.Occur.MUST); filter = booleanFilter.build(); } else { filter = percolatorTypeFilter; } Query query = Queries.filtered(context.percolateQuery(), filter); percolatorSearcher.searcher().search(query, percolateCollector); percolateCollector.aggregatorCollector.postCollection(); if (context.aggregations() != null) { aggregationPhase.execute(context); } }
8. DisMaxQParser#getUserQuery()
Project: lucene-solr
File: DisMaxQParser.java
File: DisMaxQParser.java
protected Query getUserQuery(String userQuery, SolrPluginUtils.DisjunctionMaxQueryParser up, SolrParams solrParams) throws SyntaxError { String minShouldMatch = parseMinShouldMatch(req.getSchema(), solrParams); Query dis = up.parse(userQuery); Query query = dis; if (dis instanceof BooleanQuery) { BooleanQuery.Builder t = new BooleanQuery.Builder(); SolrPluginUtils.flattenBooleanQuery(t, (BooleanQuery) dis); boolean mmAutoRelax = params.getBool(DisMaxParams.MM_AUTORELAX, false); SolrPluginUtils.setMinShouldMatch(t, minShouldMatch, mmAutoRelax); query = t.build(); } return query; }
9. TestSimpleQueryParser#testWeightedTerm()
Project: lucene-solr
File: TestSimpleQueryParser.java
File: TestSimpleQueryParser.java
/** test a term with field weights */ public void testWeightedTerm() throws Exception { Map<String, Float> weights = new LinkedHashMap<>(); weights.put("field0", 5f); weights.put("field1", 10f); BooleanQuery.Builder expected = new BooleanQuery.Builder(); Query field0 = new TermQuery(new Term("field0", "foo")); field0 = new BoostQuery(field0, 5f); expected.add(field0, Occur.SHOULD); Query field1 = new TermQuery(new Term("field1", "foo")); field1 = new BoostQuery(field1, 10f); expected.add(field1, Occur.SHOULD); Analyzer analyzer = new MockAnalyzer(random()); SimpleQueryParser parser = new SimpleQueryParser(analyzer, weights); assertEquals(expected.build(), parser.parse("foo")); }
10. TestSimpleQueryParser#testFuzzy()
Project: lucene-solr
File: TestSimpleQueryParser.java
File: TestSimpleQueryParser.java
/** test a fuzzy query */ public void testFuzzy() throws Exception { Query regular = new TermQuery(new Term("field", "foobar")); Query expected = new FuzzyQuery(new Term("field", "foobar"), 2); assertEquals(expected, parse("foobar~2")); assertEquals(regular, parse("foobar~")); assertEquals(regular, parse("foobar~a")); assertEquals(regular, parse("foobar~1a")); BooleanQuery.Builder bool = new BooleanQuery.Builder(); FuzzyQuery fuzzy = new FuzzyQuery(new Term("field", "foo"), LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE); bool.add(fuzzy, Occur.MUST); bool.add(new TermQuery(new Term("field", "bar")), Occur.MUST); assertEquals(bool.build(), parse("foo~" + LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE + 1 + " bar")); }
11. TestQPHelper#testStopwords()
Project: lucene-solr
File: TestQPHelper.java
File: TestQPHelper.java
public void testStopwords() throws Exception { StandardQueryParser qp = new StandardQueryParser(); CharacterRunAutomaton stopSet = new CharacterRunAutomaton(new RegExp("the|foo").toAutomaton()); qp.setAnalyzer(new MockAnalyzer(random(), MockTokenizer.SIMPLE, true, stopSet)); Query result = qp.parse("a:the OR a:foo", "a"); assertNotNull("result is null and it shouldn't be", result); assertTrue("result is not a MatchNoDocsQuery", result instanceof MatchNoDocsQuery); result = qp.parse("a:woo OR a:the", "a"); assertNotNull("result is null and it shouldn't be", result); assertTrue("result is not a TermQuery", result instanceof TermQuery); result = qp.parse("(fieldX:xxxxx OR fieldy:xxxxxxxx)^2 AND (fieldx:the OR fieldy:foo)", "a"); Query expected = new BooleanQuery.Builder().add(new TermQuery(new Term("fieldX", "xxxxx")), Occur.SHOULD).add(new TermQuery(new Term("fieldy", "xxxxxxxx")), Occur.SHOULD).build(); expected = new BoostQuery(expected, 2f); assertEquals(expected, result); }
12. TestComplexPhraseQuery#testHashcodeEquals()
Project: lucene-solr
File: TestComplexPhraseQuery.java
File: TestComplexPhraseQuery.java
public void testHashcodeEquals() throws Exception { ComplexPhraseQueryParser qp = new ComplexPhraseQueryParser(defaultFieldName, analyzer); qp.setInOrder(true); qp.setFuzzyPrefixLength(1); String qString = "\"aaa* bbb*\""; Query q = qp.parse(qString); Query q2 = qp.parse(qString); assertEquals(q.hashCode(), q2.hashCode()); assertEquals(q, q2); // SOLR-6011 qp.setInOrder(false); q2 = qp.parse(qString); // although the general contract of hashCode can't guarantee different values, if we only change one thing // about a single query, it normally should result in a different value (and will with the current // implementation in ComplexPhraseQuery) assertTrue(q.hashCode() != q2.hashCode()); assertTrue(!q.equals(q2)); assertTrue(!q2.equals(q)); }
13. TestComplexPhraseQuery#testToStringContainsSlop()
Project: lucene-solr
File: TestComplexPhraseQuery.java
File: TestComplexPhraseQuery.java
public void testToStringContainsSlop() throws Exception { ComplexPhraseQueryParser qp = new ComplexPhraseQueryParser(defaultFieldName, analyzer); int slop = random().nextInt(31) + 1; String qString = "name:\"j* smyth~\"~" + slop; Query query = qp.parse(qString); assertTrue("Slop is not shown in toString()", query.toString().endsWith("~" + slop)); String string = "\"j* smyth~\""; Query q = qp.parse(string); assertEquals("Don't show implicit slop of zero", q.toString(), string); }
14. TestQueryParser#testCJKSynonymsAND()
Project: lucene-solr
File: TestQueryParser.java
File: TestQueryParser.java
/** synonyms with default AND operator */ public void testCJKSynonymsAND() throws Exception { BooleanQuery.Builder expectedB = new BooleanQuery.Builder(); expectedB.add(new TermQuery(new Term(FIELD, "?")), BooleanClause.Occur.MUST); Query inner = new SynonymQuery(new Term(FIELD, "?"), new Term(FIELD, "?")); expectedB.add(inner, BooleanClause.Occur.MUST); Query expected = expectedB.build(); QueryParser qp = new QueryParser(FIELD, new MockCJKSynonymAnalyzer()); qp.setDefaultOperator(Operator.AND); assertEquals(expected, qp.parse("??")); expected = new BoostQuery(expected, 2f); assertEquals(expected, qp.parse("??^2")); }
15. TestQueryParser#testNewFieldQuery()
Project: lucene-solr
File: TestQueryParser.java
File: TestQueryParser.java
@Override public void testNewFieldQuery() throws Exception { /** ordinary behavior, synonyms form uncoordinated boolean query */ QueryParser dumb = new QueryParser(FIELD, new Analyzer1()); Query expanded = new SynonymQuery(new Term(FIELD, "dogs"), new Term(FIELD, "dog")); assertEquals(expanded, dumb.parse("\"dogs\"")); /** even with the phrase operator the behavior is the same */ assertEquals(expanded, dumb.parse("dogs")); /** * custom behavior, the synonyms are expanded, unless you use quote operator */ QueryParser smart = new SmartQueryParser(); assertEquals(expanded, smart.parse("dogs")); Query unexpanded = new TermQuery(new Term(FIELD, "dogs")); assertEquals(unexpanded, smart.parse("\"dogs\"")); }
16. TestValueSourceCache#tryQueryDiffTypes()
Project: lucene-solr
File: TestValueSourceCache.java
File: TestValueSourceCache.java
// These should always and forever fail, and would have failed without the fixes for 2829, but why not make // some more tests just in case??? void tryQueryDiffTypes(String template, String numbers, String[] types) throws SyntaxError { String s1 = template; String s2 = template; String[] numParts = numbers.split(","); for (int idx = 0; s1.contains("#"); ++idx) { String patV = "#v" + Integer.toString(idx); String patN = "#n" + Integer.toString(idx); s1 = s1.replace(patV, types[idx % types.length]).replace(patN, numParts[idx]); s2 = s2.replace(patV, types[(idx + 1) % types.length]).replace(patN, numParts[idx]); } Query q1 = getQuery(s1); Query q2 = getQuery(s2); QueryUtils.checkUnequal(q1, q2); }
17. SolrIndexSearcher#numDocs()
Project: lucene-solr
File: SolrIndexSearcher.java
File: SolrIndexSearcher.java
/** * Returns the number of documents that match both <code>a</code> and <code>b</code>. * <p> * This method is cache-aware and may check as well as modify the cache. * * @return the number of documents in the intersection between <code>a</code> and <code>b</code>. * @throws IOException * If there is a low-level I/O error. */ public int numDocs(Query a, Query b) throws IOException { Query absA = QueryUtils.getAbs(a); Query absB = QueryUtils.getAbs(b); DocSet positiveA = getPositiveDocSet(absA); DocSet positiveB = getPositiveDocSet(absB); // Negative query if absolute value different from original if (a == absA) { if (b == absB) return positiveA.intersectionSize(positiveB); return positiveA.andNotSize(positiveB); } if (b == absB) return positiveB.andNotSize(positiveA); // if both negative, we need to create a temp DocSet since we // don't have a counting method that takes three. DocSet all = getLiveDocs(); // we use the last form since the intermediate DocSet should normally be smaller. return all.andNotSize(positiveA.union(positiveB)); }
18. BlockJoinParentQParser#parse()
Project: lucene-solr
File: BlockJoinParentQParser.java
File: BlockJoinParentQParser.java
@Override public Query parse() throws SyntaxError { String filter = localParams.get(getParentFilterLocalParamName()); String scoreMode = localParams.get("score", ScoreMode.None.name()); QParser parentParser = subQuery(filter, null); Query parentQ = parentParser.getQuery(); String queryText = localParams.get(QueryParsing.V); // there is no child query, return parent filter from cache if (queryText == null || queryText.length() == 0) { SolrConstantScoreQuery wrapped = new SolrConstantScoreQuery(getFilter(parentQ)); wrapped.setCache(false); return wrapped; } QParser childrenParser = subQuery(queryText, null); Query childrenQuery = childrenParser.getQuery(); return createQuery(parentQ, childrenQuery, scoreMode); }
19. HighlighterTest#testSpanHighlighting()
Project: lucene-solr
File: HighlighterTest.java
File: HighlighterTest.java
public void testSpanHighlighting() throws Exception { Query query1 = new SpanNearQuery(new SpanQuery[] { new SpanTermQuery(new Term(FIELD_NAME, "wordx")), new SpanTermQuery(new Term(FIELD_NAME, "wordy")) }, 1, false); Query query2 = new SpanNearQuery(new SpanQuery[] { new SpanTermQuery(new Term(FIELD_NAME, "wordy")), new SpanTermQuery(new Term(FIELD_NAME, "wordc")) }, 1, false); BooleanQuery.Builder bquery = new BooleanQuery.Builder(); bquery.add(query1, Occur.SHOULD); bquery.add(query2, Occur.SHOULD); doSearching(bquery.build()); TestHighlightRunner helper = new TestHighlightRunner() { @Override public void run() throws Exception { mode = QUERY; doStandardHighlights(analyzer, searcher, hits, query, HighlighterTest.this); } }; helper.run(); assertTrue("Failed to find correct number of highlights " + numHighlights + " found", numHighlights == 7); }
20. TestSpanSearchEquivalence#testSpanWithinVsContaining()
Project: lucene-solr
File: TestSpanSearchEquivalence.java
File: TestSpanSearchEquivalence.java
/** SpanWithinQuery(A, B) = SpanContainingQuery(A, B) */ public void testSpanWithinVsContaining() throws Exception { Term t1 = randomTerm(); Term t2 = randomTerm(); SpanQuery subquery[] = new SpanQuery[] { spanQuery(new SpanTermQuery(t1)), spanQuery(new SpanTermQuery(t2)) }; SpanQuery nearQuery = spanQuery(new SpanNearQuery(subquery, 10, true)); Term t3 = randomTerm(); SpanQuery termQuery = spanQuery(new SpanTermQuery(t3)); Query q1 = spanQuery(new SpanWithinQuery(nearQuery, termQuery)); Query q2 = spanQuery(new SpanContainingQuery(nearQuery, termQuery)); assertSameSet(q1, q2); }
21. TestSpanSearchEquivalence#testSpanFirstNearEverything()
Project: lucene-solr
File: TestSpanSearchEquivalence.java
File: TestSpanSearchEquivalence.java
/** SpanFirstQuery([A B], ?) = SpanNearQuery([A B]) */ public void testSpanFirstNearEverything() throws Exception { Term t1 = randomTerm(); Term t2 = randomTerm(); SpanQuery subquery[] = new SpanQuery[] { spanQuery(new SpanTermQuery(t1)), spanQuery(new SpanTermQuery(t2)) }; SpanQuery nearQuery = spanQuery(new SpanNearQuery(subquery, 10, true)); Query q1 = spanQuery(new SpanFirstQuery(nearQuery, Integer.MAX_VALUE)); Query q2 = nearQuery; assertSameSet(q1, q2); }
22. TestSpanSearchEquivalence#testSpanRangeNearEverything()
Project: lucene-solr
File: TestSpanSearchEquivalence.java
File: TestSpanSearchEquivalence.java
/** SpanPositionRangeQuery([A B], ?) = SpanNearQuery([A B]) */ public void testSpanRangeNearEverything() throws Exception { Term t1 = randomTerm(); Term t2 = randomTerm(); SpanQuery subquery[] = new SpanQuery[] { spanQuery(new SpanTermQuery(t1)), spanQuery(new SpanTermQuery(t2)) }; SpanQuery nearQuery = spanQuery(new SpanNearQuery(subquery, 10, true)); Query q1 = spanQuery(new SpanPositionRangeQuery(nearQuery, 0, Integer.MAX_VALUE)); Query q2 = nearQuery; assertSameSet(q1, q2); }
23. NameRangeQuery#rewrite()
Project: jackrabbit
File: NameRangeQuery.java
File: NameRangeQuery.java
/** * {@inheritDoc} */ public Query rewrite(IndexReader reader) throws IOException { Query q; if (version.getVersion() >= IndexFormatVersion.V3.getVersion()) { RangeQuery localNames = new RangeQuery(getLowerLocalNameTerm(), getUpperLocalNameTerm(), inclusive, cache); BooleanQuery query = new BooleanQuery(); query.add(new JackrabbitTermQuery(new Term(FieldNames.NAMESPACE_URI, getNamespaceURI())), BooleanClause.Occur.MUST); query.add(localNames, BooleanClause.Occur.MUST); q = query; } else { q = new RangeQuery(getLowerTerm(), getUpperTerm(), inclusive, cache); } return q.rewrite(reader); }
24. DescendantSelfAxisQuery#rewrite()
Project: jackrabbit
File: DescendantSelfAxisQuery.java
File: DescendantSelfAxisQuery.java
/** * {@inheritDoc} */ public Query rewrite(IndexReader reader) throws IOException { Query cQuery = contextQuery.rewrite(reader); Query sQuery = subQuery.rewrite(reader); if (contextQuery instanceof DescendantSelfAxisQuery) { DescendantSelfAxisQuery dsaq = (DescendantSelfAxisQuery) contextQuery; if (dsaq.subQueryMatchesAll()) { return new DescendantSelfAxisQuery(dsaq.getContextQuery(), sQuery, dsaq.getMinLevels() + getMinLevels()).rewrite(reader); } } if (cQuery == contextQuery && sQuery == subQuery) { return this; } else { return new DescendantSelfAxisQuery(cQuery, sQuery, minLevels); } }
25. PlainHighlighterTests#checkGeoQueryHighlighting()
Project: elasticsearch
File: PlainHighlighterTests.java
File: PlainHighlighterTests.java
public void checkGeoQueryHighlighting(Query geoQuery) throws IOException, InvalidTokenOffsetsException { Map analysers = new HashMap<String, Analyzer>(); analysers.put("text", new StandardAnalyzer()); FieldNameAnalyzer fieldNameAnalyzer = new FieldNameAnalyzer(analysers); Query termQuery = new TermQuery(new Term("text", "failure")); Query boolQuery = new BooleanQuery.Builder().add(new BooleanClause(geoQuery, BooleanClause.Occur.SHOULD)).add(new BooleanClause(termQuery, BooleanClause.Occur.SHOULD)).build(); org.apache.lucene.search.highlight.Highlighter highlighter = new org.apache.lucene.search.highlight.Highlighter(new CustomQueryScorer(boolQuery)); String fragment = highlighter.getBestFragment(fieldNameAnalyzer.tokenStream("text", "Arbitrary text field which should not cause " + "a failure"), "Arbitrary text field which should not cause a failure"); assertThat(fragment, equalTo("Arbitrary text field which should not cause a <B>failure</B>")); // TODO: This test will fail if we pass in an instance of GeoPointInBBoxQueryImpl too. Should we also find a way to work around that // or can the query not be rewritten before it is passed into the highlighter? }
26. FloatNestedSortingTests#assertAvgScoreMode()
Project: elasticsearch
File: FloatNestedSortingTests.java
File: FloatNestedSortingTests.java
protected void assertAvgScoreMode(Query parentFilter, IndexSearcher searcher, IndexFieldData.XFieldComparatorSource innerFieldComparator) throws IOException { MultiValueMode sortMode = MultiValueMode.AVG; Query childFilter = Queries.not(parentFilter); XFieldComparatorSource nestedComparatorSource = createFieldComparator("field2", sortMode, -127, createNested(searcher, parentFilter, childFilter)); Query query = new ToParentBlockJoinQuery(new ConstantScoreQuery(childFilter), new QueryBitSetProducer(parentFilter), ScoreMode.None); Sort sort = new Sort(new SortField("field2", nestedComparatorSource)); TopDocs topDocs = searcher.search(query, 5, sort); assertThat(topDocs.totalHits, equalTo(7)); assertThat(topDocs.scoreDocs.length, equalTo(5)); assertThat(topDocs.scoreDocs[0].doc, equalTo(11)); assertThat(((Number) ((FieldDoc) topDocs.scoreDocs[0]).fields[0]).intValue(), equalTo(2)); assertThat(topDocs.scoreDocs[1].doc, equalTo(7)); assertThat(((Number) ((FieldDoc) topDocs.scoreDocs[1]).fields[0]).intValue(), equalTo(2)); assertThat(topDocs.scoreDocs[2].doc, equalTo(3)); assertThat(((Number) ((FieldDoc) topDocs.scoreDocs[2]).fields[0]).intValue(), equalTo(3)); assertThat(topDocs.scoreDocs[3].doc, equalTo(15)); assertThat(((Number) ((FieldDoc) topDocs.scoreDocs[3]).fields[0]).intValue(), equalTo(3)); assertThat(topDocs.scoreDocs[4].doc, equalTo(19)); assertThat(((Number) ((FieldDoc) topDocs.scoreDocs[4]).fields[0]).intValue(), equalTo(3)); }
27. DoubleNestedSortingTests#assertAvgScoreMode()
Project: elasticsearch
File: DoubleNestedSortingTests.java
File: DoubleNestedSortingTests.java
@Override protected void assertAvgScoreMode(Query parentFilter, IndexSearcher searcher) throws IOException { MultiValueMode sortMode = MultiValueMode.AVG; Query childFilter = Queries.not(parentFilter); XFieldComparatorSource nestedComparatorSource = createFieldComparator("field2", sortMode, -127, createNested(searcher, parentFilter, childFilter)); Query query = new ToParentBlockJoinQuery(new ConstantScoreQuery(childFilter), new QueryBitSetProducer(parentFilter), ScoreMode.None); Sort sort = new Sort(new SortField("field2", nestedComparatorSource)); TopDocs topDocs = searcher.search(query, 5, sort); assertThat(topDocs.totalHits, equalTo(7)); assertThat(topDocs.scoreDocs.length, equalTo(5)); assertThat(topDocs.scoreDocs[0].doc, equalTo(11)); assertThat(((Number) ((FieldDoc) topDocs.scoreDocs[0]).fields[0]).intValue(), equalTo(2)); assertThat(topDocs.scoreDocs[1].doc, equalTo(7)); assertThat(((Number) ((FieldDoc) topDocs.scoreDocs[1]).fields[0]).intValue(), equalTo(2)); assertThat(topDocs.scoreDocs[2].doc, equalTo(3)); assertThat(((Number) ((FieldDoc) topDocs.scoreDocs[2]).fields[0]).intValue(), equalTo(3)); assertThat(topDocs.scoreDocs[3].doc, equalTo(15)); assertThat(((Number) ((FieldDoc) topDocs.scoreDocs[3]).fields[0]).intValue(), equalTo(3)); assertThat(topDocs.scoreDocs[4].doc, equalTo(19)); assertThat(((Number) ((FieldDoc) topDocs.scoreDocs[4]).fields[0]).intValue(), equalTo(3)); }
28. AbstractNumberNestedSortingTestCase#assertAvgScoreMode()
Project: elasticsearch
File: AbstractNumberNestedSortingTestCase.java
File: AbstractNumberNestedSortingTestCase.java
protected void assertAvgScoreMode(Query parentFilter, IndexSearcher searcher) throws IOException { MultiValueMode sortMode = MultiValueMode.AVG; Query childFilter = Queries.not(parentFilter); XFieldComparatorSource nestedComparatorSource = createFieldComparator("field2", sortMode, -127, createNested(searcher, parentFilter, childFilter)); Query query = new ToParentBlockJoinQuery(new ConstantScoreQuery(childFilter), new QueryBitSetProducer(parentFilter), ScoreMode.None); Sort sort = new Sort(new SortField("field2", nestedComparatorSource)); TopDocs topDocs = searcher.search(query, 5, sort); assertThat(topDocs.totalHits, equalTo(7)); assertThat(topDocs.scoreDocs.length, equalTo(5)); assertThat(topDocs.scoreDocs[0].doc, equalTo(11)); assertThat(((Number) ((FieldDoc) topDocs.scoreDocs[0]).fields[0]).intValue(), equalTo(2)); assertThat(topDocs.scoreDocs[1].doc, equalTo(3)); assertThat(((Number) ((FieldDoc) topDocs.scoreDocs[1]).fields[0]).intValue(), equalTo(3)); assertThat(topDocs.scoreDocs[2].doc, equalTo(7)); assertThat(((Number) ((FieldDoc) topDocs.scoreDocs[2]).fields[0]).intValue(), equalTo(3)); assertThat(topDocs.scoreDocs[3].doc, equalTo(15)); assertThat(((Number) ((FieldDoc) topDocs.scoreDocs[3]).fields[0]).intValue(), equalTo(3)); assertThat(topDocs.scoreDocs[4].doc, equalTo(19)); assertThat(((Number) ((FieldDoc) topDocs.scoreDocs[4]).fields[0]).intValue(), equalTo(4)); }
29. MultiMatchQueryTests#testBlendTermsUnsupportedValue()
Project: elasticsearch
File: MultiMatchQueryTests.java
File: MultiMatchQueryTests.java
public void testBlendTermsUnsupportedValue() { FakeFieldType ft1 = new FakeFieldType(); ft1.setName("foo"); FakeFieldType ft2 = new FakeFieldType() { @Override public Query termQuery(Object value, QueryShardContext context) { throw new IllegalArgumentException(); } }; ft2.setName("bar"); Term[] terms = new Term[] { new Term("foo", "baz") }; float[] boosts = new float[] { 2 }; Query expected = BlendedTermQuery.booleanBlendedQuery(terms, boosts, false); Query actual = MultiMatchQuery.blendTerm(new BytesRef("baz"), null, 1f, new FieldAndFieldType(ft1, 2), new FieldAndFieldType(ft2, 3)); assertEquals(expected, actual); }
30. MultiMatchQueryTests#testBlendTermsWithFieldBoosts()
Project: elasticsearch
File: MultiMatchQueryTests.java
File: MultiMatchQueryTests.java
public void testBlendTermsWithFieldBoosts() { FakeFieldType ft1 = new FakeFieldType(); ft1.setName("foo"); ft1.setBoost(100); FakeFieldType ft2 = new FakeFieldType(); ft2.setName("bar"); ft2.setBoost(10); Term[] terms = new Term[] { new Term("foo", "baz"), new Term("bar", "baz") }; float[] boosts = new float[] { 200, 30 }; Query expected = BlendedTermQuery.booleanBlendedQuery(terms, boosts, false); Query actual = MultiMatchQuery.blendTerm(new BytesRef("baz"), null, 1f, new FieldAndFieldType(ft1, 2), new FieldAndFieldType(ft2, 3)); assertEquals(expected, actual); }
31. DefaultSearchContext#searchFilter()
Project: elasticsearch
File: DefaultSearchContext.java
File: DefaultSearchContext.java
@Override @Nullable public Query searchFilter(String[] types) { Query typesFilter = createSearchFilter(types, aliasFilter, mapperService().hasNested()); if (sliceBuilder == null) { return typesFilter; } Query sliceFilter = sliceBuilder.toFilter(queryShardContext, shardTarget().getShardId().getId(), queryShardContext.getIndexSettings().getNumberOfShards()); if (typesFilter == null) { return sliceFilter; } return new BooleanQuery.Builder().add(typesFilter, Occur.FILTER).add(sliceFilter, Occur.FILTER).build(); }
32. DefaultSearchContext#buildFilteredQuery()
Project: elasticsearch
File: DefaultSearchContext.java
File: DefaultSearchContext.java
private ParsedQuery buildFilteredQuery() { Query searchFilter = searchFilter(queryShardContext.getTypes()); if (searchFilter == null) { return originalQuery; } Query result; if (Queries.isConstantMatchAllQuery(query())) { result = new ConstantScoreQuery(searchFilter); } else { result = new BooleanQuery.Builder().add(query, Occur.MUST).add(searchFilter, Occur.FILTER).build(); } return new ParsedQuery(result, originalQuery); }
33. FunctionScoreQuery#rewrite()
Project: elasticsearch
File: FunctionScoreQuery.java
File: FunctionScoreQuery.java
@Override public Query rewrite(IndexReader reader) throws IOException { Query rewritten = super.rewrite(reader); if (rewritten != this) { return rewritten; } Query newQ = subQuery.rewrite(reader); if (newQ == subQuery) { return this; } return new FunctionScoreQuery(newQ, function, minScore, combineFunction, maxBoost); }
34. SimpleQueryMaker#prepareQueries()
Project: lucene-solr
File: SimpleQueryMaker.java
File: SimpleQueryMaker.java
/** * Prepare the queries for this test. * Extending classes can override this method for preparing different queries. * @return prepared queries. * @throws Exception if cannot prepare the queries. */ @Override protected Query[] prepareQueries() throws Exception { // analyzer (default is standard analyzer) Analyzer anlzr = NewAnalyzerTask.createAnalyzer(config.get("analyzer", "org.apache.lucene.analysis.standard.StandardAnalyzer")); QueryParser qp = new QueryParser(DocMaker.BODY_FIELD, anlzr); ArrayList<Query> qq = new ArrayList<>(); Query q1 = new TermQuery(new Term(DocMaker.ID_FIELD, "doc2")); qq.add(q1); Query q2 = new TermQuery(new Term(DocMaker.BODY_FIELD, "simple")); qq.add(q2); BooleanQuery.Builder bq = new BooleanQuery.Builder(); bq.add(q1, Occur.MUST); bq.add(q2, Occur.MUST); qq.add(bq.build()); qq.add(qp.parse("synthetic body")); qq.add(qp.parse("\"synthetic body\"")); qq.add(qp.parse("synthetic text")); qq.add(qp.parse("\"synthetic text\"")); qq.add(qp.parse("\"synthetic text\"~3")); qq.add(qp.parse("zoom*")); qq.add(qp.parse("synth*")); return qq.toArray(new Query[0]); }
35. WildcardCondition#query()
Project: stratio-cassandra
File: WildcardCondition.java
File: WildcardCondition.java
/** {@inheritDoc} */ @Override public Query query(Schema schema) { if (field == null || field.trim().isEmpty()) { throw new IllegalArgumentException("Field name required"); } if (value == null || value.trim().isEmpty()) { throw new IllegalArgumentException("Field value required"); } ColumnMapperSingle<?> columnMapper = getMapper(schema, field); Class<?> clazz = columnMapper.baseClass(); Query query; if (clazz == String.class) { Term term = new Term(field, value); query = new WildcardQuery(term); } else { String message = String.format("Wildcard queries are not supported by %s mapper", clazz.getSimpleName()); throw new UnsupportedOperationException(message); } query.setBoost(boost); return query; }
36. RegexpCondition#query()
Project: stratio-cassandra
File: RegexpCondition.java
File: RegexpCondition.java
/** {@inheritDoc} */ @Override public Query query(Schema schema) { if (field == null || field.trim().isEmpty()) { throw new IllegalArgumentException("Field name required"); } if (value == null || value.trim().isEmpty()) { throw new IllegalArgumentException("Field value required"); } ColumnMapperSingle<?> columnMapper = getMapper(schema, field); Class<?> clazz = columnMapper.baseClass(); Query query; if (clazz == String.class) { Term term = new Term(field, value); query = new RegexpQuery(term); } else { String message = String.format("Regexp queries are not supported by %s mapper", clazz.getSimpleName()); throw new UnsupportedOperationException(message); } query.setBoost(boost); return query; }
37. PrefixCondition#query()
Project: stratio-cassandra
File: PrefixCondition.java
File: PrefixCondition.java
/** {@inheritDoc} */ @Override public Query query(Schema schema) { if (field == null || field.trim().isEmpty()) { throw new IllegalArgumentException("Field name required"); } if (value == null) { throw new IllegalArgumentException("Field value required"); } ColumnMapperSingle<?> columnMapper = getMapper(schema, field); Class<?> clazz = columnMapper.baseClass(); Query query; if (clazz == String.class) { Term term = new Term(field, value); query = new PrefixQuery(term); } else { String message = String.format("Prefix queries are not supported by %s mapper", clazz.getSimpleName()); throw new UnsupportedOperationException(message); } query.setBoost(boost); return query; }
38. KeywordQueryParserTest#testMailtoURI()
Project: SIREn
File: KeywordQueryParserTest.java
File: KeywordQueryParserTest.java
@Test public void testMailtoURI() throws Exception { final HashMap<ConfigurationKey, Object> config = new HashMap<ConfigurationKey, Object>(); final Map<String, Analyzer> dts = new HashMap<String, Analyzer>(); dts.put("ws", new WhitespaceAnalyzer(LuceneTestCase.TEST_VERSION_CURRENT)); config.put(KeywordConfigurationKeys.DATATYPES_ANALYZERS, dts); final Query q1 = ntq("mailto:[email protected]").setDatatype("ws").getLuceneProxyQuery(); this._assertSirenQuery(config, q1, "ws('mailto:[email protected]')"); final Query q2 = bq(must(ntq("mailto:[email protected]").setDatatype("ws")), must(ntq("domain:dbpedia.org").setDatatype("ws"))).getQuery(); this._assertSirenQuery(config, q2, "ws('mailto:[email protected]' 'domain:dbpedia.org')"); }
39. KeywordQueryParserTest#testRemoveTopLevelQueryNode()
Project: SIREn
File: KeywordQueryParserTest.java
File: KeywordQueryParserTest.java
@Test public void testRemoveTopLevelQueryNode() throws Exception { // Twigs are disabled final HashMap<ConfigurationKey, Object> config = new HashMap<ConfigurationKey, Object>(); config.put(KeywordConfigurationKeys.ALLOW_TWIG, false); final HashMap<String, Analyzer> dtAnalyzers = new HashMap<String, Analyzer>(); dtAnalyzers.put(XSDDatatype.XSD_STRING, new WhitespaceAnalyzer(LuceneTestCase.TEST_VERSION_CURRENT)); config.put(KeywordConfigurationKeys.DATATYPES_ANALYZERS, dtAnalyzers); final Query q1 = nbq(must("a"), must("b"), should("c")).getNodeQuery(); this._assertSirenQuery(config, q1, "+a +\"b\" OR \"c\""); // Twigs are enabled config.put(KeywordConfigurationKeys.ALLOW_TWIG, true); final Query q2 = bq(must("a"), must("b"), should("c")).getQuery(); this._assertSirenQuery(config, q2, "+a +\"b\" OR \"c\""); }
40. BoostQueryNodeBuilder#build()
Project: SIREn
File: BoostQueryNodeBuilder.java
File: BoostQueryNodeBuilder.java
public Query build(final QueryNode queryNode) throws QueryNodeException { final BoostQueryNode boostNode = (BoostQueryNode) queryNode; final QueryNode child = boostNode.getChild(); if (child == null) { return null; } final Query query = (Query) child.getTag(QueryTreeBuilder.QUERY_TREE_BUILDER_TAGID); query.setBoost(boostNode.getValue()); return query; }
41. TestTupleQuery#testLuceneBooleanMust()
Project: SIREn
File: TestTupleQuery.java
File: TestTupleQuery.java
/** * <code>+{+[+actor]} +{+[+actor]}</code> */ @Test public void testLuceneBooleanMust() throws IOException { this.addDocument("<actor> \"actor 1\" <birthdate> \"456321\" . " + "<actor> \"actor 2\" <birthdate> \"456321\" . "); this.addDocument("<actor> \"actor 1\" . <actor> \"actor 2\" . "); final Query tq1 = tuple().with(nbq(must("actor")).bound(0, 0)).getLuceneProxyQuery(); final Query tq2 = tuple().with(nbq(must("actor")).bound(1, 1)).getLuceneProxyQuery(); final BooleanQuery bq = new BooleanQuery(); bq.add(tq1, Occur.MUST); bq.add(tq2, Occur.MUST); assertEquals(2, searcher.search(bq, 100).totalHits); }
42. TestTupleQuery#testParenthesisShould()
Project: SIREn
File: TestTupleQuery.java
File: TestTupleQuery.java
/** * <code>{[bbb eee]} {[ccc eee]}</code> */ @Test public void testParenthesisShould() throws IOException { this.addDocument("\"bbb eee\" . \"ccc eee\" . "); this.addDocument("\"bbb\" . \"aaa\" . "); this.addDocument("\"eee\" . \"aaa\" . "); this.addDocument("\"aaa\" . \"ccc\" . "); this.addDocument("\"aaa\" . \"eee\" . "); final Query tq1 = tuple().optional(nbq(should("bbb"), should("eee"))).getLuceneProxyQuery(); final Query tq2 = tuple().optional(nbq(should("ccc"), should("eee"))).getLuceneProxyQuery(); final BooleanQuery q = new BooleanQuery(); q.add(tq1, BooleanClause.Occur.SHOULD); q.add(tq2, BooleanClause.Occur.SHOULD); assertEquals(5, searcher.search(q, 100).totalHits); }
43. TestNodeBooleanScorer#testParenthesisShould()
Project: SIREn
File: TestNodeBooleanScorer.java
File: TestNodeBooleanScorer.java
/** * <code>cell(ddd ccc) cell(eee ccc)</code> */ @Test public void testParenthesisShould() throws IOException { this.addDocument("\"bbb\" . \"ddd eee\" . "); final Query nested1 = nbq(should("ddd"), should("ccc")).getLuceneProxyQuery(); final Query nested2 = nbq(should("eee"), should("ccc")).getLuceneProxyQuery(); final BooleanQuery q = new BooleanQuery(); q.add(nested1, BooleanClause.Occur.SHOULD); q.add(nested2, BooleanClause.Occur.SHOULD); assertEquals(1, searcher.search(q, 10).totalHits); }
44. TestBooleanQuery#testReqOptTuple()
Project: SIREn
File: TestBooleanQuery.java
File: TestBooleanQuery.java
@Test public void testReqOptTuple() throws CorruptIndexException, IOException { for (int i = 0; i < 10; i++) { this.addDocument("<subj> <aaa> <bbb> . <subj> <ccc> <ddd> . "); this.addDocument("<subj> <aaa> <bbb> . "); } final Query nested1 = tuple().with(nbq(must("aaa")).bound(1, 1)).with(nbq(must("bbb")).bound(2, 2)).getLuceneProxyQuery(); final Query nested2 = tuple().with(nbq(must("ccc")).bound(1, 1)).with(nbq(must("ddd")).bound(2, 2)).getLuceneProxyQuery(); final BooleanQuery q = new BooleanQuery(); q.add(nested1, Occur.MUST); q.add(nested2, Occur.SHOULD); assertEquals(20, searcher.search(q, 10).totalHits); }
45. TestBooleanQuery#testReqTuple()
Project: SIREn
File: TestBooleanQuery.java
File: TestBooleanQuery.java
@Test public void testReqTuple() throws CorruptIndexException, IOException { for (int i = 0; i < 10; i++) { this.addDocument("<subj> <aaa> <bbb> . <subj> <ccc> <ddd> . "); this.addDocument("<subj> <aaa> <bbb> . "); } final Query nested1 = tuple().with(nbq(must("aaa")).bound(1, 1)).with(nbq(must("bbb")).bound(2, 2)).getLuceneProxyQuery(); final Query nested2 = tuple().with(nbq(must("ccc")).bound(1, 1)).with(nbq(must("ddd")).bound(2, 2)).getLuceneProxyQuery(); final BooleanQuery q = new BooleanQuery(); q.add(nested1, Occur.MUST); q.add(nested2, Occur.MUST); assertEquals(10, searcher.search(q, 10).totalHits); }
46. AbstractLuceneQuery#createQuery()
Project: querydsl
File: AbstractLuceneQuery.java
File: AbstractLuceneQuery.java
protected Query createQuery() { Query returnedQuery = null; Query originalQuery = null; if (queryMixin.getMetadata().getWhere() == null) { originalQuery = new MatchAllDocsQuery(); } else { originalQuery = serializer.toQuery(queryMixin.getMetadata().getWhere(), queryMixin.getMetadata()); } Filter filter = getFilter(); if (filter != null) { BooleanQuery booleanQuery = new BooleanQuery(); booleanQuery.add(originalQuery, Occur.MUST); booleanQuery.add(filter, Occur.FILTER); returnedQuery = booleanQuery; } else { returnedQuery = originalQuery; } return returnedQuery; }
47. BlendedTermQuery#rewrite()
Project: elassandra
File: BlendedTermQuery.java
File: BlendedTermQuery.java
@Override public Query rewrite(IndexReader reader) throws IOException { IndexReaderContext context = reader.getContext(); TermContext[] ctx = new TermContext[terms.length]; int[] docFreqs = new int[ctx.length]; for (int i = 0; i < terms.length; i++) { ctx[i] = TermContext.build(context, terms[i]); docFreqs[i] = ctx[i].docFreq(); } final int maxDoc = reader.maxDoc(); blend(ctx, maxDoc, reader); Query query = topLevelQuery(terms, ctx, docFreqs, maxDoc); query.setBoost(getBoost()); return query; }
48. Solr4QueryParser#getDoesNotMatchFieldQuery()
Project: community-edition
File: Solr4QueryParser.java
File: Solr4QueryParser.java
public Query getDoesNotMatchFieldQuery(String field, String queryText, AnalysisMode analysisMode, LuceneFunction luceneFunction) throws ParseException { BooleanQuery query = new BooleanQuery(); Query allQuery = new MatchAllDocsQuery(); Query matchQuery = getFieldQuery(field, queryText, analysisMode, luceneFunction); if ((matchQuery != null)) { query.add(allQuery, Occur.MUST); query.add(matchQuery, Occur.MUST_NOT); } else { throw new UnsupportedOperationException(); } return query; }
49. AbstractLuceneQueryParser#getDoesNotMatchFieldQuery()
Project: community-edition
File: AbstractLuceneQueryParser.java
File: AbstractLuceneQueryParser.java
public Query getDoesNotMatchFieldQuery(String field, String queryText, AnalysisMode analysisMode, LuceneFunction luceneFunction) throws ParseException { BooleanQuery query = new BooleanQuery(); Query allQuery = new MatchAllDocsQuery(); Query matchQuery = getFieldQuery(field, queryText, analysisMode, luceneFunction); if ((matchQuery != null)) { query.add(allQuery, Occur.MUST); query.add(matchQuery, Occur.MUST_NOT); } else { throw new UnsupportedOperationException(); } return query; }
50. IndexService#searcher()
Project: cassandra-lucene-index
File: IndexService.java
File: IndexService.java
/** * Returns a new {@link Index.Searcher} for the specified {@link ReadCommand}. * * @param command the read command being executed * @return a searcher with which to perform the supplied command */ Index.Searcher searcher(ReadCommand command) { // Parse search Tracer.trace("Building Lucene search"); String expression = expression(command); Search search = SearchBuilder.fromJson(expression).build(); Query query = search.query(schema, query(command).orElse(null)); Query after = after(search.paging(), command); Sort sort = sort(search); int count = command.limits().count(); // Refresh if required if (search.refresh()) { Tracer.trace("Refreshing Lucene index searcher"); refresh(); } // Search Tracer.trace("Lucene index searching for {} rows", count); DocumentIterator documents = lucene.search(after, query, sort, count); return (ReadOrderGroup orderGroup) -> indexReader(documents, command, orderGroup); }
51. QueryBuilder#createMinShouldMatchQuery()
Project: lucene-solr
File: QueryBuilder.java
File: QueryBuilder.java
/** * Creates a minimum-should-match query from the query text. * <p> * @param field field name * @param queryText text to be passed to the analyzer * @param fraction of query terms {@code [0..1]} that should match * @return {@code TermQuery} or {@code BooleanQuery}, based on the analysis * of {@code queryText} */ public Query createMinShouldMatchQuery(String field, String queryText, float fraction) { if (Float.isNaN(fraction) || fraction < 0 || fraction > 1) { throw new IllegalArgumentException("fraction should be >= 0 and <= 1"); } // TODO: wierd that BQ equals/rewrite/scorer doesn't handle this? if (fraction == 1) { return createBooleanQuery(field, queryText, BooleanClause.Occur.MUST); } Query query = createFieldQuery(analyzer, BooleanClause.Occur.SHOULD, field, queryText, false, 0); if (query instanceof BooleanQuery) { BooleanQuery bq = (BooleanQuery) query; BooleanQuery.Builder builder = new BooleanQuery.Builder(); builder.setMinimumNumberShouldMatch((int) (fraction * bq.clauses().size())); for (BooleanClause clause : bq) { builder.add(clause); } query = builder.build(); } return query; }
52. IndexWriter#deleteDocuments()
Project: lucene-solr
File: IndexWriter.java
File: IndexWriter.java
/** * Deletes the document(s) matching any of the provided queries. * All given deletes are applied and flushed atomically at the same time. * * @return The <a href="#sequence_number">sequence number</a> * for this operation * * @param queries array of queries to identify the documents * to be deleted * @throws CorruptIndexException if the index is corrupt * @throws IOException if there is a low-level IO error */ public long deleteDocuments(Query... queries) throws IOException { ensureOpen(); // LUCENE-6379: Specialize MatchAllDocsQuery for (Query query : queries) { if (query.getClass() == MatchAllDocsQuery.class) { return deleteAll(); } } try { long seqNo = docWriter.deleteQueries(queries); if (seqNo < 0) { seqNo = -seqNo; processEvents(true, false); } return seqNo; } catch (VirtualMachineError tragedy) { tragicEvent(tragedy, "deleteDocuments(Query..)"); return -1; } }
53. KNearestNeighborClassifier#knnSearch()
Project: lucene-solr
File: KNearestNeighborClassifier.java
File: KNearestNeighborClassifier.java
private TopDocs knnSearch(String text) throws IOException { BooleanQuery.Builder mltQuery = new BooleanQuery.Builder(); for (String fieldName : textFieldNames) { String boost = null; //terms boost actually helps in MLT queries mlt.setBoost(true); if (fieldName.contains("^")) { String[] field2boost = fieldName.split("\\^"); fieldName = field2boost[0]; boost = field2boost[1]; } if (boost != null) { //if we have a field boost, we add it mlt.setBoostFactor(Float.parseFloat(boost)); } mltQuery.add(new BooleanClause(mlt.like(fieldName, new StringReader(text)), BooleanClause.Occur.SHOULD)); // restore neutral boost for next field mlt.setBoostFactor(1); } Query classFieldQuery = new WildcardQuery(new Term(classFieldName, "*")); mltQuery.add(new BooleanClause(classFieldQuery, BooleanClause.Occur.MUST)); if (query != null) { mltQuery.add(query, BooleanClause.Occur.MUST); } return indexSearcher.search(mltQuery.build(), k); }
54. SearchTravRetVectorHighlightTask#getBenchmarkHighlighter()
Project: lucene-solr
File: SearchTravRetVectorHighlightTask.java
File: SearchTravRetVectorHighlightTask.java
@Override protected BenchmarkHighlighter getBenchmarkHighlighter(Query q) { highlighter = new FastVectorHighlighter(false, false); final Query myq = q; return new BenchmarkHighlighter() { @Override public int doHighlight(IndexReader reader, int doc, String field, Document document, Analyzer analyzer, String text) throws Exception { final FieldQuery fq = highlighter.getFieldQuery(myq, reader); String[] fragments = highlighter.getBestFragments(fq, reader, doc, field, fragSize, maxFrags); return fragments != null ? fragments.length : 0; } }; }
55. SpatialFileQueryMaker#makeQueryFromShape()
Project: lucene-solr
File: SpatialFileQueryMaker.java
File: SpatialFileQueryMaker.java
protected Query makeQueryFromShape(Shape shape) { SpatialArgs args = new SpatialArgs(operation, shape); if (!Double.isNaN(distErrPct)) args.setDistErrPct(distErrPct); Query filterQuery = strategy.makeQuery(args); if (score) { //wrap with distance computing query ValueSource valueSource = strategy.makeDistanceValueSource(shape.getCenter()); return new BooleanQuery.Builder().add(new FunctionQuery(valueSource), //matches everything and provides score BooleanClause.Occur.MUST).add(filterQuery, //filters (score isn't used) BooleanClause.Occur.FILTER).build(); } else { // assume constant scoring return filterQuery; } }
56. TranslationMemoryServiceImpl#generateTransMemoryQuery()
Project: zanata-server
File: TranslationMemoryServiceImpl.java
File: TranslationMemoryServiceImpl.java
/** * Generates the Hibernate Search Query that will search for * {@link org.zanata.model.tm.TransMemoryUnit} objects for matches. * * @param sourceLocale * @param targetLocale * @param queryText * @return */ private Query generateTransMemoryQuery(LocaleId sourceLocale, LocaleId targetLocale, String queryText) throws ParseException { // Analyzer determined by the language String analyzerDefName = TextContainerAnalyzerDiscriminator.getAnalyzerDefinitionName(sourceLocale.getId()); Analyzer analyzer = entityManager.getSearchFactory().getAnalyzer(analyzerDefName); QueryParser parser = new QueryParser(LUCENE_VERSION, IndexFieldLabels.TRANS_UNIT_VARIANT_FIELD + sourceLocale.getId(), analyzer); Query sourceContentQuery = parser.parse(queryText); WildcardQuery targetContentQuery = new WildcardQuery(new Term(IndexFieldLabels.TRANS_UNIT_VARIANT_FIELD + targetLocale.getId(), "*")); return join(BooleanClause.Occur.MUST, sourceContentQuery, targetContentQuery); }
57. TranslationMemoryServiceImpl#generateQuery()
Project: zanata-server
File: TranslationMemoryServiceImpl.java
File: TranslationMemoryServiceImpl.java
/** * Generate the query to match all source contents in all the searchable * indexes. (HTextFlowTarget and TransMemoryUnit) * * @param query * @param sourceLocale * @param targetLocale * @param queryText * @param multiQueryText * @param srcContentFields * @return * @throws ParseException */ private Query generateQuery(TransMemoryQuery query, LocaleId sourceLocale, LocaleId targetLocale, Optional<Long> textFlowTargetId, String queryText, String[] multiQueryText, String srcContentFields[]) throws ParseException { Query textFlowTargetQuery = generateTextFlowTargetQuery(query, sourceLocale, targetLocale, textFlowTargetId, queryText, multiQueryText, srcContentFields); if (query.getSearchType() == HasSearchType.SearchType.CONTENT_HASH) { return textFlowTargetQuery; } else { String tmQueryText = query.getSearchType() == HasSearchType.SearchType.FUZZY_PLURAL ? multiQueryText[0] : queryText; Query transUnitQuery = generateTransMemoryQuery(sourceLocale, targetLocale, tmQueryText); // Join the queries for each different type return join(BooleanClause.Occur.SHOULD, textFlowTargetQuery, transUnitQuery); } }
58. ExodusLuceneWithPatriciaTests#addSearchPhraseTestQuery()
Project: xodus
File: ExodusLuceneWithPatriciaTests.java
File: ExodusLuceneWithPatriciaTests.java
@Test public void addSearchPhraseTestQuery() throws IOException, ParseException { addSearchMatch(); Query query = getQuery(DESCRIPTION, "\"could now start selling\""); Assert.assertTrue(query instanceof PhraseQuery); TopDocs docs = indexSearcher.search(query, Integer.MAX_VALUE); Assert.assertEquals(1, docs.totalHits); query = getQuery(DESCRIPTION, "\"the fourth stage\""); Assert.assertTrue(query instanceof PhraseQuery); docs = indexSearcher.search(query, Integer.MAX_VALUE); Assert.assertEquals(1, docs.totalHits); removeStopWord("on"); query = getQuery(DESCRIPTION, "\"on the plane\""); Assert.assertTrue(query instanceof PhraseQuery); docs = indexSearcher.search(query, Integer.MAX_VALUE); Assert.assertEquals(0, docs.totalHits); removeStopWord("as"); query = getQuery(DESCRIPTION, "\"as a player\""); Assert.assertTrue(query instanceof PhraseQuery); docs = indexSearcher.search(query, Integer.MAX_VALUE); Assert.assertEquals(0, docs.totalHits); }
59. Searcher#getDocumentForLabel()
Project: Web-Karma
File: Searcher.java
File: Searcher.java
public Document getDocumentForLabel(String label) throws IOException { Query query = new TermQuery(new Term(Indexer.LABEL_FIELD_NAME, label)); TopDocs results = indexSearcher.search(query, 10); ScoreDoc[] hits = results.scoreDocs; for (int i = 0; i < hits.length; i++) { Document doc = indexSearcher.doc(hits[i].doc); String labelString = doc.get(Indexer.LABEL_FIELD_NAME); if (// document for labelString.equalsIgnoreCase(label)) // exact semantic // label already // exists { return doc; } } return null; }
60. Searcher#getTopK()
Project: Web-Karma
File: Searcher.java
File: Searcher.java
public List<SemanticTypeLabel> getTopK(int k, String content) throws ParseException, IOException { List<SemanticTypeLabel> result = new ArrayList<>(); content = content.toLowerCase().replaceAll("and", " ").replaceAll("or", " ").replaceAll("\\+", "").replaceAll("\\-", ""); int spaces = content.length() - content.replace(" ", "").length(); if (spaces > BooleanQuery.getMaxClauseCount()) { BooleanQuery.setMaxClauseCount(spaces); } //System.out.println("Query: " + content); Query query = parser.parse(QueryParser.escape(content)); TopDocs results = indexSearcher.search(query, k); ScoreDoc[] hits = results.scoreDocs; for (int i = 0; i < hits.length; i++) { Document doc = indexSearcher.doc(hits[i].doc); String labelString = doc.get(Indexer.LABEL_FIELD_NAME); result.add(new SemanticTypeLabel(labelString, hits[i].score)); } return result; }
61. WildcardConditionTest#testInetV6()
Project: stratio-cassandra
File: WildcardConditionTest.java
File: WildcardConditionTest.java
@Test public void testInetV6() { Map<String, ColumnMapper> map = new HashMap<>(); map.put("name", new ColumnMapperInet()); Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName()); WildcardCondition wildcardCondition = new WildcardCondition(0.5f, "name", "2001:db8:2de:0:0:0:0:e*"); Query query = wildcardCondition.query(mappers); Assert.assertNotNull(query); Assert.assertEquals(org.apache.lucene.search.WildcardQuery.class, query.getClass()); org.apache.lucene.search.WildcardQuery luceneQuery = (org.apache.lucene.search.WildcardQuery) query; Assert.assertEquals("name", luceneQuery.getField()); Assert.assertEquals("2001:db8:2de:0:0:0:0:e*", luceneQuery.getTerm().text()); Assert.assertEquals(0.5f, query.getBoost(), 0); }
62. WildcardConditionTest#testInetV4()
Project: stratio-cassandra
File: WildcardConditionTest.java
File: WildcardConditionTest.java
@Test public void testInetV4() { Map<String, ColumnMapper> map = new HashMap<>(); map.put("name", new ColumnMapperInet()); Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName()); WildcardCondition wildcardCondition = new WildcardCondition(0.5f, "name", "192.168.*"); Query query = wildcardCondition.query(mappers); Assert.assertNotNull(query); Assert.assertEquals(org.apache.lucene.search.WildcardQuery.class, query.getClass()); org.apache.lucene.search.WildcardQuery luceneQuery = (org.apache.lucene.search.WildcardQuery) query; Assert.assertEquals("name", luceneQuery.getField()); Assert.assertEquals("192.168.*", luceneQuery.getTerm().text()); Assert.assertEquals(0.5f, query.getBoost(), 0); }
63. WildcardConditionTest#testString()
Project: stratio-cassandra
File: WildcardConditionTest.java
File: WildcardConditionTest.java
@Test public void testString() { Map<String, ColumnMapper> map = new HashMap<>(); map.put("name", new ColumnMapperString()); Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName()); WildcardCondition wildcardCondition = new WildcardCondition(0.5f, "name", "tr*"); Query query = wildcardCondition.query(mappers); Assert.assertNotNull(query); Assert.assertEquals(org.apache.lucene.search.WildcardQuery.class, query.getClass()); org.apache.lucene.search.WildcardQuery luceneQuery = (org.apache.lucene.search.WildcardQuery) query; Assert.assertEquals("name", luceneQuery.getField()); Assert.assertEquals("tr*", luceneQuery.getTerm().text()); Assert.assertEquals(0.5f, query.getBoost(), 0); }
64. RangeConditionTest#testInetV6()
Project: stratio-cassandra
File: RangeConditionTest.java
File: RangeConditionTest.java
@Test public void testInetV6() { Map<String, ColumnMapper> map = new HashMap<>(); map.put("name", new ColumnMapperInet()); Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName()); RangeCondition rangeCondition = range("name").boost(0.5f).lower("2001:DB8:2de::e13").upper("2001:DB8:02de::e23").includeLower(true).includeUpper(true).build(); Query query = rangeCondition.query(mappers); Assert.assertNotNull(query); Assert.assertEquals(TermRangeQuery.class, query.getClass()); Assert.assertEquals("name", ((TermRangeQuery) query).getField()); Assert.assertEquals("2001:db8:2de:0:0:0:0:e13", ((TermRangeQuery) query).getLowerTerm().utf8ToString()); Assert.assertEquals("2001:db8:2de:0:0:0:0:e23", ((TermRangeQuery) query).getUpperTerm().utf8ToString()); Assert.assertEquals(true, ((TermRangeQuery) query).includesLower()); Assert.assertEquals(true, ((TermRangeQuery) query).includesUpper()); Assert.assertEquals(0.5f, query.getBoost(), 0); }
65. RangeConditionTest#testInetV4()
Project: stratio-cassandra
File: RangeConditionTest.java
File: RangeConditionTest.java
@Test public void testInetV4() { Map<String, ColumnMapper> map = new HashMap<>(); map.put("name", new ColumnMapperInet()); Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName()); RangeCondition rangeCondition = new RangeCondition(0.5f, "name", "192.168.0.01", "192.168.0.045", true, true); Query query = rangeCondition.query(mappers); Assert.assertNotNull(query); Assert.assertEquals(TermRangeQuery.class, query.getClass()); Assert.assertEquals("name", ((TermRangeQuery) query).getField()); Assert.assertEquals("192.168.0.1", ((TermRangeQuery) query).getLowerTerm().utf8ToString()); Assert.assertEquals("192.168.0.45", ((TermRangeQuery) query).getUpperTerm().utf8ToString()); Assert.assertEquals(true, ((TermRangeQuery) query).includesLower()); Assert.assertEquals(true, ((TermRangeQuery) query).includesUpper()); Assert.assertEquals(0.5f, query.getBoost(), 0); }
66. RangeConditionTest#testDoubleOpen()
Project: stratio-cassandra
File: RangeConditionTest.java
File: RangeConditionTest.java
@Test public void testDoubleOpen() { Map<String, ColumnMapper> map = new HashMap<>(); map.put("name", new ColumnMapperDouble(1f)); Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName()); RangeCondition rangeCondition = new RangeCondition(0.5f, "name", 42.42D, null, true, false); Query query = rangeCondition.query(mappers); Assert.assertNotNull(query); Assert.assertEquals(NumericRangeQuery.class, query.getClass()); Assert.assertEquals("name", ((NumericRangeQuery<?>) query).getField()); Assert.assertEquals(42.42D, ((NumericRangeQuery<?>) query).getMin()); Assert.assertEquals(null, ((NumericRangeQuery<?>) query).getMax()); Assert.assertEquals(true, ((NumericRangeQuery<?>) query).includesMin()); Assert.assertEquals(false, ((NumericRangeQuery<?>) query).includesMax()); Assert.assertEquals(0.5f, query.getBoost(), 0); }
67. RangeConditionTest#testDoubleClose()
Project: stratio-cassandra
File: RangeConditionTest.java
File: RangeConditionTest.java
@Test public void testDoubleClose() { Map<String, ColumnMapper> map = new HashMap<>(); map.put("name", new ColumnMapperDouble(1f)); Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName()); RangeCondition rangeCondition = new RangeCondition(0.5f, "name", 42.42D, 43.42D, false, false); Query query = rangeCondition.query(mappers); Assert.assertNotNull(query); Assert.assertEquals(NumericRangeQuery.class, query.getClass()); Assert.assertEquals("name", ((NumericRangeQuery<?>) query).getField()); Assert.assertEquals(42.42D, ((NumericRangeQuery<?>) query).getMin()); Assert.assertEquals(43.42D, ((NumericRangeQuery<?>) query).getMax()); Assert.assertEquals(false, ((NumericRangeQuery<?>) query).includesMin()); Assert.assertEquals(false, ((NumericRangeQuery<?>) query).includesMax()); Assert.assertEquals(0.5f, query.getBoost(), 0); }
68. RangeConditionTest#testFloatOpen()
Project: stratio-cassandra
File: RangeConditionTest.java
File: RangeConditionTest.java
@Test public void testFloatOpen() { Map<String, ColumnMapper> map = new HashMap<>(); map.put("name", new ColumnMapperFloat(1f)); Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName()); RangeCondition rangeCondition = new RangeCondition(0.5f, "name", 42.42f, null, true, false); Query query = rangeCondition.query(mappers); Assert.assertNotNull(query); Assert.assertEquals(NumericRangeQuery.class, query.getClass()); Assert.assertEquals("name", ((NumericRangeQuery<?>) query).getField()); Assert.assertEquals(42.42f, ((NumericRangeQuery<?>) query).getMin()); Assert.assertEquals(null, ((NumericRangeQuery<?>) query).getMax()); Assert.assertEquals(true, ((NumericRangeQuery<?>) query).includesMin()); Assert.assertEquals(false, ((NumericRangeQuery<?>) query).includesMax()); Assert.assertEquals(0.5f, query.getBoost(), 0); }
69. RangeConditionTest#testFloatClose()
Project: stratio-cassandra
File: RangeConditionTest.java
File: RangeConditionTest.java
@Test public void testFloatClose() { Map<String, ColumnMapper> map = new HashMap<>(); map.put("name", new ColumnMapperFloat(1f)); Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName()); RangeCondition rangeCondition = new RangeCondition(0.5f, "name", 42.42D, 43.42F, false, false); Query query = rangeCondition.query(mappers); Assert.assertNotNull(query); Assert.assertEquals(NumericRangeQuery.class, query.getClass()); Assert.assertEquals("name", ((NumericRangeQuery<?>) query).getField()); Assert.assertEquals(42.42F, ((NumericRangeQuery<?>) query).getMin()); Assert.assertEquals(43.42f, ((NumericRangeQuery<?>) query).getMax()); Assert.assertEquals(false, ((NumericRangeQuery<?>) query).includesMin()); Assert.assertEquals(false, ((NumericRangeQuery<?>) query).includesMax()); Assert.assertEquals(0.5f, query.getBoost(), 0); }
70. RangeConditionTest#testLongOpen()
Project: stratio-cassandra
File: RangeConditionTest.java
File: RangeConditionTest.java
@Test public void testLongOpen() { Map<String, ColumnMapper> map = new HashMap<>(); map.put("name", new ColumnMapperLong(1f)); Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName()); RangeCondition rangeCondition = new RangeCondition(0.5f, "name", 42f, null, true, false); Query query = rangeCondition.query(mappers); Assert.assertNotNull(query); Assert.assertEquals(NumericRangeQuery.class, query.getClass()); Assert.assertEquals("name", ((NumericRangeQuery<?>) query).getField()); Assert.assertEquals(42L, ((NumericRangeQuery<?>) query).getMin()); Assert.assertEquals(null, ((NumericRangeQuery<?>) query).getMax()); Assert.assertEquals(true, ((NumericRangeQuery<?>) query).includesMin()); Assert.assertEquals(false, ((NumericRangeQuery<?>) query).includesMax()); Assert.assertEquals(0.5f, query.getBoost(), 0); }
71. RangeConditionTest#testLongClose()
Project: stratio-cassandra
File: RangeConditionTest.java
File: RangeConditionTest.java
@Test public void testLongClose() { Map<String, ColumnMapper> map = new HashMap<>(); map.put("name", new ColumnMapperLong(1f)); Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName()); RangeCondition rangeCondition = new RangeCondition(0.5f, "name", 42L, 43, false, false); Query query = rangeCondition.query(mappers); Assert.assertNotNull(query); Assert.assertEquals(NumericRangeQuery.class, query.getClass()); Assert.assertEquals("name", ((NumericRangeQuery<?>) query).getField()); Assert.assertEquals(42L, ((NumericRangeQuery<?>) query).getMin()); Assert.assertEquals(43L, ((NumericRangeQuery<?>) query).getMax()); Assert.assertEquals(false, ((NumericRangeQuery<?>) query).includesMin()); Assert.assertEquals(false, ((NumericRangeQuery<?>) query).includesMax()); Assert.assertEquals(0.5f, query.getBoost(), 0); }
72. RangeConditionTest#testIntegerOpen()
Project: stratio-cassandra
File: RangeConditionTest.java
File: RangeConditionTest.java
@Test public void testIntegerOpen() { Map<String, ColumnMapper> map = new HashMap<>(); map.put("name", new ColumnMapperInteger(1f)); Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName()); RangeCondition rangeCondition = new RangeCondition(0.5f, "name", 42, null, true, false); Query query = rangeCondition.query(mappers); Assert.assertNotNull(query); Assert.assertEquals(NumericRangeQuery.class, query.getClass()); Assert.assertEquals("name", ((NumericRangeQuery<?>) query).getField()); Assert.assertEquals(42, ((NumericRangeQuery<?>) query).getMin()); Assert.assertEquals(null, ((NumericRangeQuery<?>) query).getMax()); Assert.assertEquals(true, ((NumericRangeQuery<?>) query).includesMin()); Assert.assertEquals(false, ((NumericRangeQuery<?>) query).includesMax()); Assert.assertEquals(0.5f, query.getBoost(), 0); }
73. RangeConditionTest#testIntegerClose()
Project: stratio-cassandra
File: RangeConditionTest.java
File: RangeConditionTest.java
@Test public void testIntegerClose() { Map<String, ColumnMapper> map = new HashMap<>(); map.put("name", new ColumnMapperInteger(1f)); Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName()); RangeCondition rangeCondition = new RangeCondition(0.5f, "name", 42, 43, false, false); Query query = rangeCondition.query(mappers); Assert.assertNotNull(query); Assert.assertEquals(NumericRangeQuery.class, query.getClass()); Assert.assertEquals("name", ((NumericRangeQuery<?>) query).getField()); Assert.assertEquals(42, ((NumericRangeQuery<?>) query).getMin()); Assert.assertEquals(43, ((NumericRangeQuery<?>) query).getMax()); Assert.assertEquals(false, ((NumericRangeQuery<?>) query).includesMin()); Assert.assertEquals(false, ((NumericRangeQuery<?>) query).includesMax()); Assert.assertEquals(0.5f, query.getBoost(), 0); }
74. RangeConditionTest#testStringOpen()
Project: stratio-cassandra
File: RangeConditionTest.java
File: RangeConditionTest.java
@Test public void testStringOpen() { Map<String, ColumnMapper> map = new HashMap<>(); map.put("name", new ColumnMapperBoolean()); Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName()); RangeCondition rangeCondition = new RangeCondition(0.5f, "name", "alpha", null, true, false); Query query = rangeCondition.query(mappers); Assert.assertNotNull(query); Assert.assertEquals(TermRangeQuery.class, query.getClass()); Assert.assertEquals("name", ((TermRangeQuery) query).getField()); Assert.assertEquals("alpha", ((TermRangeQuery) query).getLowerTerm().utf8ToString()); Assert.assertEquals(null, ((TermRangeQuery) query).getUpperTerm()); Assert.assertNull(((TermRangeQuery) query).getUpperTerm()); Assert.assertEquals(true, ((TermRangeQuery) query).includesLower()); Assert.assertEquals(false, ((TermRangeQuery) query).includesUpper()); Assert.assertEquals(0.5f, query.getBoost(), 0); }
75. RangeConditionTest#testStringClose()
Project: stratio-cassandra
File: RangeConditionTest.java
File: RangeConditionTest.java
@Test public void testStringClose() { Map<String, ColumnMapper> map = new HashMap<>(); map.put("name", new ColumnMapperBoolean()); Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName()); RangeCondition rangeCondition = new RangeCondition(0.5f, "name", "alpha", "beta", true, true); Query query = rangeCondition.query(mappers); Assert.assertNotNull(query); Assert.assertEquals(TermRangeQuery.class, query.getClass()); Assert.assertEquals("name", ((TermRangeQuery) query).getField()); Assert.assertEquals("alpha", ((TermRangeQuery) query).getLowerTerm().utf8ToString()); Assert.assertEquals("beta", ((TermRangeQuery) query).getUpperTerm().utf8ToString()); Assert.assertEquals(true, ((TermRangeQuery) query).includesLower()); Assert.assertEquals(true, ((TermRangeQuery) query).includesUpper()); Assert.assertEquals(0.5f, query.getBoost(), 0); }
76. PrefixConditionTest#testInetV6()
Project: stratio-cassandra
File: PrefixConditionTest.java
File: PrefixConditionTest.java
@Test public void testInetV6() { Map<String, ColumnMapper> map = new HashMap<>(); map.put("name", new ColumnMapperInet()); Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName()); PrefixCondition wildcardCondition = new PrefixCondition(0.5f, "name", "2001:db8:2de:0:0:0:0:e"); Query query = wildcardCondition.query(mappers); Assert.assertNotNull(query); Assert.assertEquals(PrefixQuery.class, query.getClass()); PrefixQuery luceneQuery = (PrefixQuery) query; Assert.assertEquals("name", luceneQuery.getField()); Assert.assertEquals("2001:db8:2de:0:0:0:0:e", luceneQuery.getPrefix().text()); Assert.assertEquals(0.5f, query.getBoost(), 0); }
77. PrefixConditionTest#testInetV4()
Project: stratio-cassandra
File: PrefixConditionTest.java
File: PrefixConditionTest.java
@Test public void testInetV4() { Map<String, ColumnMapper> map = new HashMap<>(); map.put("name", new ColumnMapperInet()); Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName()); PrefixCondition wildcardCondition = new PrefixCondition(0.5f, "name", "192.168."); Query query = wildcardCondition.query(mappers); Assert.assertNotNull(query); Assert.assertEquals(PrefixQuery.class, query.getClass()); PrefixQuery luceneQuery = (PrefixQuery) query; Assert.assertEquals("name", luceneQuery.getField()); Assert.assertEquals("192.168.", luceneQuery.getPrefix().text()); Assert.assertEquals(0.5f, query.getBoost(), 0); }
78. PrefixConditionTest#testString()
Project: stratio-cassandra
File: PrefixConditionTest.java
File: PrefixConditionTest.java
@Test public void testString() { Map<String, ColumnMapper> map = new HashMap<>(); map.put("name", new ColumnMapperString()); Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName()); PrefixCondition prefixCondition = new PrefixCondition(0.5f, "name", "tr"); Query query = prefixCondition.query(mappers); Assert.assertNotNull(query); Assert.assertEquals(PrefixQuery.class, query.getClass()); PrefixQuery luceneQuery = (PrefixQuery) query; Assert.assertEquals("name", luceneQuery.getField()); Assert.assertEquals("tr", luceneQuery.getPrefix().text()); Assert.assertEquals(0.5f, query.getBoost(), 0); }
79. PhraseConditionTest#testPhraseQuery()
Project: stratio-cassandra
File: PhraseConditionTest.java
File: PhraseConditionTest.java
@Test public void testPhraseQuery() { Map<String, ColumnMapper> map = new HashMap<>(); map.put("name", new ColumnMapperBoolean()); Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName()); List<String> values = new ArrayList<>(); values.add("hola"); values.add("adios"); PhraseCondition phraseCondition = new PhraseCondition(0.5f, "name", values, 2); Query query = phraseCondition.query(mappers); Assert.assertNotNull(query); Assert.assertEquals(org.apache.lucene.search.PhraseQuery.class, query.getClass()); org.apache.lucene.search.PhraseQuery luceneQuery = (org.apache.lucene.search.PhraseQuery) query; Assert.assertEquals(values.size(), luceneQuery.getTerms().length); Assert.assertEquals(2, luceneQuery.getSlop()); Assert.assertEquals(0.5f, query.getBoost(), 0); }
80. MatchConditionTest#testInetV6()
Project: stratio-cassandra
File: MatchConditionTest.java
File: MatchConditionTest.java
@Test public void testInetV6() { Map<String, ColumnMapper> map = new HashMap<>(); map.put("name", new ColumnMapperInet()); Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName()); MatchCondition matchCondition = new MatchCondition(0.5f, "name", "2001:DB8:2de::0e13"); Query query = matchCondition.query(mappers); Assert.assertNotNull(query); Assert.assertEquals(TermQuery.class, query.getClass()); Assert.assertEquals("2001:db8:2de:0:0:0:0:e13", ((TermQuery) query).getTerm().bytes().utf8ToString()); Assert.assertEquals(0.5f, query.getBoost(), 0); }
81. MatchConditionTest#testInetV4()
Project: stratio-cassandra
File: MatchConditionTest.java
File: MatchConditionTest.java
@Test public void testInetV4() { Map<String, ColumnMapper> map = new HashMap<>(); map.put("name", new ColumnMapperInet()); Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName()); MatchCondition matchCondition = new MatchCondition(0.5f, "name", "192.168.0.01"); Query query = matchCondition.query(mappers); Assert.assertNotNull(query); Assert.assertEquals(TermQuery.class, query.getClass()); Assert.assertEquals("192.168.0.1", ((TermQuery) query).getTerm().bytes().utf8ToString()); Assert.assertEquals(0.5f, query.getBoost(), 0); }
82. MatchConditionTest#testBlob()
Project: stratio-cassandra
File: MatchConditionTest.java
File: MatchConditionTest.java
@Test public void testBlob() { Map<String, ColumnMapper> map = new HashMap<>(); map.put("name", new ColumnMapperBlob()); Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName()); MatchCondition matchCondition = new MatchCondition(0.5f, "name", "0Fa1"); Query query = matchCondition.query(mappers); Assert.assertNotNull(query); Assert.assertEquals(TermQuery.class, query.getClass()); Assert.assertEquals("0fa1", ((TermQuery) query).getTerm().bytes().utf8ToString()); Assert.assertEquals(0.5f, query.getBoost(), 0); }
83. MatchConditionTest#testDouble()
Project: stratio-cassandra
File: MatchConditionTest.java
File: MatchConditionTest.java
@Test public void testDouble() { Map<String, ColumnMapper> map = new HashMap<>(); map.put("name", new ColumnMapperDouble(1f)); Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName()); MatchCondition matchCondition = new MatchCondition(0.5f, "name", 42.42D); Query query = matchCondition.query(mappers); Assert.assertNotNull(query); Assert.assertEquals(NumericRangeQuery.class, query.getClass()); Assert.assertEquals(42.42D, ((NumericRangeQuery<?>) query).getMin()); Assert.assertEquals(42.42D, ((NumericRangeQuery<?>) query).getMax()); Assert.assertEquals(true, ((NumericRangeQuery<?>) query).includesMin()); Assert.assertEquals(true, ((NumericRangeQuery<?>) query).includesMax()); Assert.assertEquals(0.5f, query.getBoost(), 0); }
84. MatchConditionTest#testFloat()
Project: stratio-cassandra
File: MatchConditionTest.java
File: MatchConditionTest.java
@Test public void testFloat() { Map<String, ColumnMapper> map = new HashMap<>(); map.put("name", new ColumnMapperFloat(1f)); Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName()); MatchCondition matchCondition = new MatchCondition(0.5f, "name", 42.42F); Query query = matchCondition.query(mappers); Assert.assertNotNull(query); Assert.assertEquals(NumericRangeQuery.class, query.getClass()); Assert.assertEquals(42.42F, ((NumericRangeQuery<?>) query).getMin()); Assert.assertEquals(42.42F, ((NumericRangeQuery<?>) query).getMax()); Assert.assertEquals(true, ((NumericRangeQuery<?>) query).includesMin()); Assert.assertEquals(true, ((NumericRangeQuery<?>) query).includesMax()); Assert.assertEquals(0.5f, query.getBoost(), 0); }
85. MatchConditionTest#testLong()
Project: stratio-cassandra
File: MatchConditionTest.java
File: MatchConditionTest.java
@Test public void testLong() { Map<String, ColumnMapper> map = new HashMap<>(); map.put("name", new ColumnMapperLong(1f)); Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName()); MatchCondition matchCondition = new MatchCondition(0.5f, "name", 42L); Query query = matchCondition.query(mappers); Assert.assertNotNull(query); Assert.assertEquals(NumericRangeQuery.class, query.getClass()); Assert.assertEquals(42L, ((NumericRangeQuery<?>) query).getMin()); Assert.assertEquals(42L, ((NumericRangeQuery<?>) query).getMax()); Assert.assertEquals(true, ((NumericRangeQuery<?>) query).includesMin()); Assert.assertEquals(true, ((NumericRangeQuery<?>) query).includesMax()); Assert.assertEquals(0.5f, query.getBoost(), 0); }
86. MatchConditionTest#testInteger()
Project: stratio-cassandra
File: MatchConditionTest.java
File: MatchConditionTest.java
@Test public void testInteger() { Map<String, ColumnMapper> map = new HashMap<>(); map.put("name", new ColumnMapperInteger(1f)); Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName()); MatchCondition matchCondition = new MatchCondition(0.5f, "name", 42); Query query = matchCondition.query(mappers); Assert.assertNotNull(query); Assert.assertEquals(NumericRangeQuery.class, query.getClass()); Assert.assertEquals(42, ((NumericRangeQuery<?>) query).getMin()); Assert.assertEquals(42, ((NumericRangeQuery<?>) query).getMax()); Assert.assertEquals(true, ((NumericRangeQuery<?>) query).includesMin()); Assert.assertEquals(true, ((NumericRangeQuery<?>) query).includesMax()); Assert.assertEquals(0.5f, query.getBoost(), 0); }
87. MatchConditionTest#testString()
Project: stratio-cassandra
File: MatchConditionTest.java
File: MatchConditionTest.java
@Test public void testString() { Map<String, ColumnMapper> map = new HashMap<>(); map.put("name", new ColumnMapperString()); Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName()); MatchCondition matchCondition = new MatchCondition(0.5f, "name", "casa"); Query query = matchCondition.query(mappers); Assert.assertNotNull(query); Assert.assertEquals(TermQuery.class, query.getClass()); Assert.assertEquals("casa", ((TermQuery) query).getTerm().bytes().utf8ToString()); Assert.assertEquals(0.5f, query.getBoost(), 0); }
88. FuzzyConditionTest#testFuzzyQuery()
Project: stratio-cassandra
File: FuzzyConditionTest.java
File: FuzzyConditionTest.java
@Test public void testFuzzyQuery() { Map<String, ColumnMapper> map = new HashMap<>(); map.put("name", new ColumnMapperBoolean()); Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName()); FuzzyCondition fuzzyCondition = new FuzzyCondition(0.5f, "name", "tr", 1, 2, 49, true); Query query = fuzzyCondition.query(mappers); Assert.assertNotNull(query); Assert.assertEquals(org.apache.lucene.search.FuzzyQuery.class, query.getClass()); org.apache.lucene.search.FuzzyQuery luceneQuery = (org.apache.lucene.search.FuzzyQuery) query; Assert.assertEquals("name", luceneQuery.getField()); Assert.assertEquals("tr", luceneQuery.getTerm().text()); Assert.assertEquals(1, luceneQuery.getMaxEdits()); Assert.assertEquals(2, luceneQuery.getPrefixLength()); Assert.assertEquals(0.5f, query.getBoost(), 0); }
89. NGramQueryParserTest#testFreeFormQueryParse()
Project: spacewalk
File: NGramQueryParserTest.java
File: NGramQueryParserTest.java
public void testFreeFormQueryParse() throws Exception { String queryString = new String("name:spell -description:another"); log.info("Original query: " + queryString); NGramQueryParser parser = new NGramQueryParser("name", new NGramAnalyzer(min_ngram, max_ngram), true); Query q = parser.parse(queryString); log.info("NGramQueryParser parsed query: " + q.toString()); QueryParser origParser = new QueryParser("name", new StandardAnalyzer()); q = origParser.parse(queryString); log.info("QueryParser parsed query = " + q.toString()); }
90. NGramQueryParserTest#performSearch()
Project: spacewalk
File: NGramQueryParserTest.java
File: NGramQueryParserTest.java
public Hits performSearch(Directory dir, String query, boolean useMust) throws Exception { NGramQueryParser parser = new NGramQueryParser("name", new NGramAnalyzer(min_ngram, max_ngram), useMust); IndexSearcher searcher = new IndexSearcher(dir); Query q = parser.parse(query); Hits hits = searcher.search(q); log.info("Original Query = " + query); log.info("Parsed Query = " + q.toString()); log.info("Hits.length() = " + hits.length()); for (int i = 0; i < hits.length(); i++) { log.debug("Document<" + hits.id(i) + "> = " + hits.doc(i)); //Explanation explain = searcher.explain(q, hits.id(i)); //log.debug("explain = " + explain.toString()); } return hits; }
91. NGramQueryParser#getFieldQuery()
Project: spacewalk
File: NGramQueryParser.java
File: NGramQueryParser.java
protected Query getFieldQuery(String defaultField, String queryText) throws ParseException { Query orig = super.getFieldQuery(defaultField, queryText); if (!(orig instanceof PhraseQuery)) { log.debug("Returning default query. No phrase query translation."); return orig; } /** * A ngram when parsed will become a series of smaller search terms, * these terms are grouped together into a PhraseQuery. We are taking * that PhraseQuery and breaking out each ngram term then combining all * ngrams together to form a BooleanQuery. */ PhraseQuery pq = (PhraseQuery) orig; return new NGramQuery(pq, useMust); }
92. KeywordQueryParserTest#testNestedArrayQuery()
Project: SIREn
File: KeywordQueryParserTest.java
File: KeywordQueryParserTest.java
@Test public void testNestedArrayQuery() throws Exception { final Query q = twq(1).with(ntq("b")).with(twq(2).with(ntq("c")).with(ntq("d"))).getLuceneProxyQuery(); this._assertSirenQuery(q, "* : [ b, * : [ c, d ] ]"); this._assertSirenQuery(q, "* : [ b, [ c , d ] ]"); }
93. KeywordQueryParserTest#testArrayQueryWithModifiers2()
Project: SIREn
File: KeywordQueryParserTest.java
File: KeywordQueryParserTest.java
@Test public void testArrayQueryWithModifiers2() throws Exception { final Query q = twq(1).with(twq(2).with(ntq("aaa")).with(ntq("b"))).without(twq(2).with(ntq("c")).with(ntq("d"))).getLuceneProxyQuery(); this._assertSirenQuery(q, "* : [ * : [ aaa, b ], -(*:[ c, d ]) ]"); }
94. KeywordQueryParserTest#testPrefixQuery()
Project: SIREn
File: KeywordQueryParserTest.java
File: KeywordQueryParserTest.java
@Test public void testPrefixQuery() throws Exception { final Query ntq = new LuceneProxyNodeQuery(new NodePrefixQuery(new Term(SirenTestCase.DEFAULT_TEST_FIELD, "lit"))); this._assertSirenQuery(ntq, "lit*"); final TwigQuery twq = new TwigQuery(1); twq.addChild(new NodePrefixQuery(new Term(SirenTestCase.DEFAULT_TEST_FIELD, "lit")), NodeBooleanClause.Occur.MUST); this._assertSirenQuery(new LuceneProxyNodeQuery(twq), "* : lit*"); }
95. KeywordQueryParserTest#testTwigQueryLineFeed()
Project: SIREn
File: KeywordQueryParserTest.java
File: KeywordQueryParserTest.java
@Test public void testTwigQueryLineFeed() throws Exception { final HashMap<ConfigurationKey, Object> config = new HashMap<ConfigurationKey, Object>(); final Map<String, Analyzer> dts = new HashMap<String, Analyzer>(); dts.put(XSDDatatype.XSD_STRING, new WhitespaceAnalyzer(LuceneTestCase.TEST_VERSION_CURRENT)); dts.put("ws", new WhitespaceAnalyzer(LuceneTestCase.TEST_VERSION_CURRENT)); config.put(KeywordConfigurationKeys.DATATYPES_ANALYZERS, dts); final Query bq = bq(must(twq(1).with(ntq("literal"))), must(twq(1).with(ntq("http://o.org").setDatatype("ws")))).getQuery(); this._assertSirenQuery(config, bq, "(* : literal) AND\r\n (* \n\r : \n ws('http://o.org'))"); }
96. KeywordQueryParserTest#testTwigComplement2()
Project: SIREn
File: KeywordQueryParserTest.java
File: KeywordQueryParserTest.java
/** * SRN-91 */ @Test public void testTwigComplement2() throws Exception { final HashMap<ConfigurationKey, Object> config = new HashMap<ConfigurationKey, Object>(); final Map<String, Analyzer> dts = new HashMap<String, Analyzer>(); dts.put("ws", new WhitespaceAnalyzer(LuceneTestCase.TEST_VERSION_CURRENT)); dts.put(JSONDatatype.JSON_FIELD, new StandardAnalyzer(LuceneTestCase.TEST_VERSION_CURRENT)); config.put(KeywordConfigurationKeys.DATATYPES_ANALYZERS, dts); final Query bq = bq(must(twq(1).with(ntq("literal").setDatatype("ws"))), not(twq(1).with(ntq("http://o.org").setDatatype("ws")))).getQuery(); this._assertSirenQuery(config, bq, "ws((* : literal) NOT (* : 'http://o.org'))"); }
97. KeywordQueryParserTest#testTwigQueriesComplement()
Project: SIREn
File: KeywordQueryParserTest.java
File: KeywordQueryParserTest.java
@Test public void testTwigQueriesComplement() throws Exception { final Query bq = bq(must(twq(1).root(ntq("aaa")).with(ntq("c"))), not(twq(1).root(ntq("b")).with(ntq("d")))).getQuery(); this._assertSirenQuery(bq, "(aaa : c) - (b : d)"); }
98. KeywordQueryParserTest#testTwigQueryDatatypeOnRoot()
Project: SIREn
File: KeywordQueryParserTest.java
File: KeywordQueryParserTest.java
@Test public void testTwigQueryDatatypeOnRoot() throws Exception { final HashMap<ConfigurationKey, Object> config = new HashMap<ConfigurationKey, Object>(); final Map<String, Analyzer> dts = new HashMap<String, Analyzer>(); dts.put("ws", new WhitespaceAnalyzer(LuceneTestCase.TEST_VERSION_CURRENT)); config.put(KeywordConfigurationKeys.DATATYPES_ANALYZERS, dts); // json:field is always applied on the top level node of the twig. final Query q = twq(1).root(ntq("AAA").setDatatype("ws")).with(ntq("b").setDatatype("ws")).getLuceneProxyQuery(); this._assertSirenQuery(config, q, "ws(AAA) : ws(b)"); this._assertSirenQuery(config, q, "ws(AAA : b)"); }
99. KeywordQueryParserTest#testTwigQueryDatatype()
Project: SIREn
File: KeywordQueryParserTest.java
File: KeywordQueryParserTest.java
@Test public void testTwigQueryDatatype() throws Exception { final HashMap<ConfigurationKey, Object> config = new HashMap<ConfigurationKey, Object>(); final Map<String, Analyzer> dts = new HashMap<String, Analyzer>(); dts.put("ws", new WhitespaceAnalyzer(LuceneTestCase.TEST_VERSION_CURRENT)); dts.put(JSONDatatype.JSON_FIELD, new StandardAnalyzer(LuceneTestCase.TEST_VERSION_CURRENT)); config.put(KeywordConfigurationKeys.DATATYPES_ANALYZERS, dts); // json:field is always applied on the top level node of the twig. final Query q = twq(1).root(ntq("aaa")).with(ntq("b").setDatatype("ws")).getLuceneProxyQuery(); this._assertSirenQuery(config, q, "AAA : ws(b)"); }
100. KeywordQueryParserTest#testNestedGroups2()
Project: SIREn
File: KeywordQueryParserTest.java
File: KeywordQueryParserTest.java
@Test public void testNestedGroups2() throws Exception { final Query q = bq(must(ntq("test")), must(bq(must(bq(should(ntq("literal")), must(ntq("uri")), not(ntq("resource"))), bq(should(ntq("pattern")), must(ntq("patterns")), not(ntq("query"))))))).getQuery(); this._assertSirenQuery(q, "Test AND ((literal OR +uri OR -resource) AND (pattern OR +patterns OR -query))"); }