Java Code Examples for org.apache.solr.search.QueryParsing

The following examples show how to use org.apache.solr.search.QueryParsing. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: solr-redis   Source File: TestRedisQParser.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAddTermsFromSortLimitAndOffset() throws SyntaxError, IOException {
  when(localParamsMock.get("command")).thenReturn("sort");
  when(localParamsMock.get("key")).thenReturn("simpleKey");
  when(localParamsMock.get("offset")).thenReturn("100");
  when(localParamsMock.get("limit")).thenReturn("1000");
  when(localParamsMock.get(QueryParsing.V)).thenReturn("string_field");
  when(jedisMock.sort(anyString(), any(SortingParams.class))).thenReturn(Arrays.asList("123", "321"));
  when(requestMock.getSchema()).thenReturn(schema);
  when(schema.getQueryAnalyzer()).thenReturn(new StandardAnalyzer());
  redisQParser = new RedisQParser("string_field", localParamsMock, paramsMock, requestMock, commandHandler);
  final Query query = redisQParser.parse();
  final ArgumentCaptor<SortingParams> argument = ArgumentCaptor.forClass(SortingParams.class);
  verify(jedisMock).sort(eq("simpleKey"), argument.capture());
  Assert.assertEquals(getSortingParamString(new SortingParams().limit(100, 1000)),
      getSortingParamString(argument.getValue()));
  IndexSearcher searcher = new IndexSearcher(new MultiReader());
  final Set<Term> terms = extractTerms(searcher, query);
  Assert.assertEquals(2, terms.size());
}
 
Example 2
Source Project: solr-redis   Source File: TestRedisQParser.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnEmptyQueryOnEmptyResultOfLindex() throws SyntaxError, IOException {
  when(localParamsMock.get("command")).thenReturn("lindex");
  when(localParamsMock.get("index")).thenReturn("10");
  when(localParamsMock.get("key")).thenReturn("simpleKey");
  when(localParamsMock.get(QueryParsing.V)).thenReturn("string_field");
  when(jedisMock.lindex(anyString(), anyLong())).thenReturn(null);
  when(requestMock.getSchema()).thenReturn(schema);
  when(schema.getQueryAnalyzer()).thenReturn(new StandardAnalyzer());
  redisQParser = new RedisQParser("string_field", localParamsMock, paramsMock, requestMock, commandHandler);
  final Query query = redisQParser.parse();
  verify(jedisMock).lindex("simpleKey", 10);
  IndexSearcher searcher = new IndexSearcher(new MultiReader());
  final Set<Term> terms = extractTerms(searcher, query);
  Assert.assertEquals(0, terms.size());
}
 
Example 3
Source Project: solr-redis   Source File: TestRedisQParser.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAddTermsFromSort() throws SyntaxError, IOException {
  when(localParamsMock.get("command")).thenReturn("sort");
  when(localParamsMock.get("key")).thenReturn("simpleKey");
  when(localParamsMock.get(QueryParsing.V)).thenReturn("string_field");
  when(jedisMock.sort(anyString(), any(SortingParams.class))).thenReturn(Arrays.asList("123", "321"));
  when(requestMock.getSchema()).thenReturn(schema);
  when(schema.getQueryAnalyzer()).thenReturn(new StandardAnalyzer());
  redisQParser = new RedisQParser("string_field", localParamsMock, paramsMock, requestMock, commandHandler);
  final Query query = redisQParser.parse();
  final ArgumentCaptor<SortingParams> argument = ArgumentCaptor.forClass(SortingParams.class);
  verify(jedisMock).sort(eq("simpleKey"), argument.capture());
  Assert.assertEquals(getSortingParamString(new SortingParams()), getSortingParamString(argument.getValue()));
  IndexSearcher searcher = new IndexSearcher(new MultiReader());
  final Set<Term> terms = extractTerms(searcher, query);
  Assert.assertEquals(2, terms.size());
}
 
Example 4
Source Project: lucene-solr   Source File: HighlightComponent.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void prepare(ResponseBuilder rb) throws IOException {
  SolrParams params = rb.req.getParams();
  rb.doHighlights = solrConfigHighlighter.isHighlightingEnabled(params);
  if(rb.doHighlights){
    rb.setNeedDocList(true);
    String hlq = params.get(HighlightParams.Q);
    String hlparser = MoreObjects.firstNonNull(params.get(HighlightParams.QPARSER),
                                            params.get(QueryParsing.DEFTYPE, QParserPlugin.DEFAULT_QTYPE));
    if(hlq != null){
      try {
        QParser parser = QParser.getParser(hlq, hlparser, rb.req);
        rb.setHighlightQuery(parser.getHighlightQuery());
      } catch (SyntaxError e) {
        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e);
      }
    }
  }
}
 
Example 5
Source Project: lucene-solr   Source File: QueryElevationComponent.java    License: Apache License 2.0 6 votes vote down vote up
protected Elevation getElevation(ResponseBuilder rb) {
  SolrParams localParams = rb.getQparser().getLocalParams();
  String queryString = localParams == null ? rb.getQueryString() : localParams.get(QueryParsing.V);
  if (queryString == null || rb.getQuery() == null) {
    return null;
  }

  SolrParams params = rb.req.getParams();
  String paramElevatedIds = params.get(QueryElevationParams.IDS);
  String paramExcludedIds = params.get(QueryElevationParams.EXCLUDE);
  try {
    if (paramElevatedIds != null || paramExcludedIds != null) {
      List<String> elevatedIds = paramElevatedIds != null ? StrUtils.splitSmart(paramElevatedIds,",", true) : Collections.emptyList();
      List<String> excludedIds = paramExcludedIds != null ? StrUtils.splitSmart(paramExcludedIds, ",", true) : Collections.emptyList();
      return new ElevationBuilder().addElevatedIds(elevatedIds).addExcludedIds(excludedIds).build();
    } else {
      IndexReader reader = rb.req.getSearcher().getIndexReader();
      return getElevationProvider(reader, rb.req.getCore()).getElevationForQuery(queryString);
    }
  } catch (Exception e) {
    throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Error loading elevation", e);
  }
}
 
Example 6
Source Project: solr-redis   Source File: TestRedisQParser.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAddTermsFromRedisOnZrangebyscoreCommandWithCustomRange() throws SyntaxError, IOException {
  when(localParamsMock.get("command")).thenReturn("zrangebyscore");
  when(localParamsMock.get("key")).thenReturn("simpleKey");
  when(localParamsMock.get("min")).thenReturn("1");
  when(localParamsMock.get("max")).thenReturn("100");
  when(localParamsMock.get(QueryParsing.V)).thenReturn("string_field");
  when(jedisMock.zrangeByScoreWithScores(anyString(), anyString(), anyString()))
      .thenReturn(new HashSet<>(Arrays.asList(new Tuple("123", (double) 1.0f), new Tuple("321", (double) 1.0f))));
  when(requestMock.getSchema()).thenReturn(schema);
  when(schema.getQueryAnalyzer()).thenReturn(new StandardAnalyzer());
  redisQParser = new RedisQParser("string_field", localParamsMock, paramsMock, requestMock, commandHandler);
  final Query query = redisQParser.parse();
  verify(jedisMock).zrangeByScoreWithScores("simpleKey", "1", "100");
  IndexSearcher searcher = new IndexSearcher(new MultiReader());
  final Set<Term> terms = extractTerms(searcher, query);
  Assert.assertEquals(2, terms.size());
}
 
Example 7
Source Project: lucene-solr   Source File: SolrPluginUtils.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"unchecked"})
public static void doStandardQueryDebug(
        SolrQueryRequest req,
        String userQuery,
        Query query,
        boolean dbgQuery,
        @SuppressWarnings({"rawtypes"})NamedList dbg)
{
  if (dbgQuery) {
    /* userQuery may have been pre-processed .. expose that */
    dbg.add("rawquerystring", req.getParams().get(CommonParams.Q));
    dbg.add("querystring", userQuery);

   /* QueryParsing.toString isn't perfect, use it to see converted
    * values, use regular toString to see any attributes of the
    * underlying Query it may have missed.
    */
    dbg.add("parsedquery", QueryParsing.toString(query, req.getSchema()));
    dbg.add("parsedquery_toString", query.toString());
  }
}
 
Example 8
Source Project: chronix.server   Source File: ChronixRetentionHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Searches the index, if older documents exists. Updates the solr query response.
 *
 * @param req - the solr query request information
 * @param rsp - the solr query response information
 * @return true if the hit count is greater zero, otherwise false
 * @throws SyntaxError, IOException if bad things happen
 */
private boolean olderDocumentsExists(String queryString, SolrQueryRequest req, SolrQueryResponse rsp) throws SyntaxError, IOException {
    String defType = req.getParams().get(QueryParsing.DEFTYPE, QParserPlugin.DEFAULT_QTYPE);

    QParser queryParser = QParser.getParser(queryString, defType, req);
    Query query = queryParser.getQuery();

    TotalHitCountCollector totalHitCountCollector = new TotalHitCountCollector();
    req.getSearcher().search(query, totalHitCountCollector);

    rsp.add("query", String.format("%s:[* TO NOW-%s]", queryField, timeSeriesAge));
    rsp.add("queryTechnical", queryString);
    rsp.add("removedDocuments", totalHitCountCollector.getTotalHits());

    return totalHitCountCollector.getTotalHits() != 0;
}
 
Example 9
Source Project: querqy   Source File: BoostMethodTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testThatTheDefaultBoostMethodIsOpt() {
    String q = "qup";

    SolrQueryRequest req = req("q", q,
            DisMaxParams.QF, "f1 f2",
            QueryParsing.OP, "OR",
            "defType", "querqy",
            "debugQuery", "true"
    );

    assertQ("Default boost method is not 'opt'",
            req,
            "//result[@name='response'][@numFound='2']",
            // the parsed query must contain the boost terms:
            "//str[@name='parsedquery'][contains(.,'f1:u100')]",
            "//str[@name='parsedquery'][contains(.,'f2:u100')]");
    req.close();

}
 
Example 10
Source Project: querqy   Source File: BoostMethodTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testThatOptCanBePassedAsBoostMethodParam() {
    String q = "qup";

    SolrQueryRequest req = req("q", q,
            DisMaxParams.QF, "f1 f2",
            QueryParsing.OP, "OR",
            QBOOST_METHOD, QBOOST_METHOD_OPT,
            "defType", "querqy",
            "debugQuery", "true"

    );

    assertQ("Default boost method is not 'opt'",
            req,
            "//result[@name='response'][@numFound='2']",
            // the parsed query must contain the boost terms:
            "//str[@name='parsedquery'][contains(.,'f1:u100')]",
            "//str[@name='parsedquery'][contains(.,'f2:u100')]");
    req.close();

}
 
Example 11
Source Project: querqy   Source File: BoostMethodTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testThatReRankMethodCanBeActivated() {
    String q = "qup";

    SolrQueryRequest req = req("q", q,
            DisMaxParams.QF, "f1 f2",
            QueryParsing.OP, "OR",
            QBOOST_METHOD, QBOOST_METHOD_RERANK,
            "defType", "querqy",
            "debugQuery", "true"

    );

    assertQ("Method is not 'rerank'",
            req,
            "//result[@name='response'][@numFound='2']",
            // the parsed query must contain not the boost terms:
            "//str[@name='parsedquery'][not(contains(.,'f1:u100'))]",
            "//str[@name='parsedquery'][not(contains(.,'f2:u100'))]",
            // debug output must contain 'QuerqyReRankQuery'
            "//lst[@name='explain']/str[contains(.,'QuerqyReRankQuery')]"
    );
    req.close();

}
 
Example 12
Source Project: solr-redis   Source File: TestRedisQParser.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAddTermsFromRedisOnLindexCommand() throws SyntaxError, IOException {
  when(localParamsMock.get("command")).thenReturn("lindex");
  when(localParamsMock.get("index")).thenReturn("10");
  when(localParamsMock.get("key")).thenReturn("simpleKey");
  when(localParamsMock.get(QueryParsing.V)).thenReturn("string_field");
  when(jedisMock.lindex(anyString(), anyLong())).thenReturn("value");
  when(requestMock.getSchema()).thenReturn(schema);
  when(schema.getQueryAnalyzer()).thenReturn(new StandardAnalyzer());
  redisQParser = new RedisQParser("string_field", localParamsMock, paramsMock, requestMock, commandHandler);
  final Query query = redisQParser.parse();
  verify(jedisMock).lindex("simpleKey", 10);
  IndexSearcher searcher = new IndexSearcher(new MultiReader());
  final Set<Term> terms = extractTerms(searcher, query);
  Assert.assertEquals(1, terms.size());
}
 
Example 13
Source Project: solr-redis   Source File: TestRedisQParser.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAddTermsFromSortAlgorithmAlpha() throws SyntaxError, IOException {
  when(localParamsMock.get("command")).thenReturn("sort");
  when(localParamsMock.get("key")).thenReturn("simpleKey");
  when(localParamsMock.get("algorithm")).thenReturn("alpha");
  when(localParamsMock.get(QueryParsing.V)).thenReturn("string_field");
  when(jedisMock.sort(anyString(), any(SortingParams.class))).thenReturn(Arrays.asList("123", "321"));
  when(requestMock.getSchema()).thenReturn(schema);
  when(schema.getQueryAnalyzer()).thenReturn(new StandardAnalyzer());
  redisQParser = new RedisQParser("string_field", localParamsMock, paramsMock, requestMock, commandHandler);
  final Query query = redisQParser.parse();
  final ArgumentCaptor<SortingParams> argument = ArgumentCaptor.forClass(SortingParams.class);
  verify(jedisMock).sort(eq("simpleKey"), argument.capture());
  Assert.assertEquals(getSortingParamString(new SortingParams().alpha()), getSortingParamString(argument.getValue()));
  IndexSearcher searcher = new IndexSearcher(new MultiReader());
  final Set<Term> terms = extractTerms(searcher, query);
  Assert.assertEquals(2, terms.size());
}
 
Example 14
Source Project: querqy   Source File: DefaultQuerqyDismaxQParserTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testThatMatchAllDoesNotThrowException() {
   String q = "*:*";

   SolrQueryRequest req = req("q", q,
         DisMaxParams.QF, "f1 f2",
         DisMaxParams.MM, "3",
         QueryParsing.OP, "OR",
         DisMaxParams.PF, "f3^2 f4^0.5",
         "defType", "querqy",
         "debugQuery", "true"
         );

   assertQ("Matchall fails",
         req,
         "//str[@name='parsedquery'][contains(.,'*:*')]",
         "//result[@name='response' and @numFound='11']"

   );

   req.close();
}
 
Example 15
Source Project: querqy   Source File: DefaultQuerqyDismaxQParserTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testThatPfIsAppliedOnlyToFieldsWithTermPositions() {

   String q = "a b c d";
   SolrQueryRequest req = req("q", q,
         DisMaxParams.QF, "f1 f2",
         DisMaxParams.MM, "3",
         QueryParsing.OP, "OR",
         "defType", "querqy",
         "debugQuery", "true",
         DisMaxParams.PF, "f1^1.2 str^2 f_no_tfp^0.5");

   // str is a string field
   // f_no_tfp / f_no_tp don't have term positions
   assertQ("wrong ps2",
         req,
         "//str[@name='parsedquery'][contains(.,'PhraseQuery(f1:\"a b c d\")^1.2')]",
         "//str[@name='parsedquery'][not(contains(.,'PhraseQuery(str:\"a b c d\")^2.0'))]",
         "//str[@name='parsedquery'][not(contains(.,'PhraseQuery(f_no_tfp:\"a b c d\")^0.5'))]",
         "//str[@name='parsedquery'][not(contains(.,'PhraseQuery(f_no_tp:\"a b c d\")^0.5'))]");

   req.close();

}
 
Example 16
Source Project: querqy   Source File: DefaultQuerqyDismaxQParserTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testThatAnalysisIsRunForPf() {

    String q = "K L M";
    SolrQueryRequest req = req("q", q,
            DisMaxParams.QF, "f1",
            DisMaxParams.MM, "3",
            QueryParsing.OP, "OR",
            "defType", "querqy",
            "debugQuery", "true",
            DisMaxParams.PF, "f1_lc f2_lc");


    assertQ("Analysis not applied for pf",
            req,
            // Query terms should be lower-cased in analysis for pf fields
            "//str[@name='parsedquery'][contains(.,'DisjunctionMaxQuery((f1_lc:\"k l m\" | f2_lc:\"k l m\"))')]",
            // but not for query fields
            "//str[@name='parsedquery'][contains(.,'(f1:K f1:L f1:M)')]");

    req.close();

}
 
Example 17
Source Project: querqy   Source File: DefaultQuerqyDismaxQParserTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testThatAnalysisIsRunForPf2() {

    String q = "K L M";
    SolrQueryRequest req = req("q", q,
            DisMaxParams.QF, "f1",
            DisMaxParams.MM, "3",
            QueryParsing.OP, "OR",
            "defType", "querqy",
            "debugQuery", "true",
            DisMaxParams.PF2, "f1_lc f2_lc");


    assertQ("Analysis not applied for pf2",
            req,
            // Query terms should be lower-cased in analysis for pf2 fields
            "//str[@name='parsedquery'][contains(.,'DisjunctionMaxQuery(((f1_lc:\"k l\" f1_lc:\"l m\") | (f2_lc:\"k l\" f2_lc:\"l m\")))')]",
            // but not for query fields
            "//str[@name='parsedquery'][contains(.,'(f1:K f1:L f1:M)')]");

    req.close();

}
 
Example 18
Source Project: solr-redis   Source File: TestRedisQParser.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldTurnAnalysisOn() throws SyntaxError, IOException {
  when(localParamsMock.get("command")).thenReturn("smembers");
  when(localParamsMock.get("key")).thenReturn("simpleKey");
  when(localParamsMock.getBool("useAnalyzer", false)).thenReturn(true);
  when(localParamsMock.get(QueryParsing.V)).thenReturn("string_field");
  when(requestMock.getSchema()).thenReturn(schema);
  when(schema.getQueryAnalyzer()).thenReturn(new WhitespaceAnalyzer());
  when(jedisMock.smembers(anyString())).thenReturn(new HashSet<>(Arrays.asList("123 124", "321")));
  redisQParser = new RedisQParser("string_field", localParamsMock, paramsMock, requestMock, commandHandler);
  final Query query = redisQParser.parse();
  verify(jedisMock).smembers("simpleKey");
  IndexSearcher searcher = new IndexSearcher(new MultiReader());
  final Set<Term> terms = extractTerms(searcher, query);
  Assert.assertEquals(3, terms.size());
}
 
Example 19
Source Project: querqy   Source File: DefaultQuerqyDismaxQParserTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testThatPf2IsAppliedOnlyToExistingField() {

   String q = "a b c d";
   SolrQueryRequest req = req("q", q,
         DisMaxParams.QF, "f1 f2",
         DisMaxParams.MM, "3",
         QueryParsing.OP, "OR",
         "defType", "querqy",
         "debugQuery", "true",
         DisMaxParams.PF2, "f1^2 f40^0.5");

   // f40 does not exists
   assertQ("wrong ps2",
         req,
         "//str[@name='parsedquery_toString'][contains(.,'(f1:\"a b\" f1:\"b c\" f1:\"c d\")^2.0')]",
         "//str[@name='parsedquery_toString'][not(contains(.,'(f40:\"a b\" f1:\"b c\" f1:\"c d\")^0.5'))]");

   req.close();

}
 
Example 20
Source Project: solr-redis   Source File: TestRedisQParser.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAddTermsFromRedisOnLrangeCommandEmptyStringMinAndMaxFallsBackToDefault()
    throws SyntaxError, IOException {
  when(localParamsMock.get("command")).thenReturn("lrange");
  when(localParamsMock.get("min")).thenReturn(" ");
  when(localParamsMock.get("min")).thenReturn("   ");
  when(localParamsMock.get("key")).thenReturn("simpleKey");
  when(localParamsMock.get(QueryParsing.V)).thenReturn("string_field");
  when(jedisMock.lrange(anyString(), anyLong(), anyLong())).thenReturn(Arrays.asList("123", "321"));
  when(requestMock.getSchema()).thenReturn(schema);
  when(schema.getQueryAnalyzer()).thenReturn(new StandardAnalyzer());
  redisQParser = new RedisQParser("string_field", localParamsMock, paramsMock, requestMock, commandHandler);
  final Query query = redisQParser.parse();
  verify(jedisMock).lrange("simpleKey", 0, -1);
  IndexSearcher searcher = new IndexSearcher(new MultiReader());
  final Set<Term> terms = extractTerms(searcher, query);
  Assert.assertEquals(2, terms.size());
}
 
Example 21
Source Project: querqy   Source File: DefaultQuerqyDismaxQParserTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testThatPFSkipsMustNotClauses() throws Exception {

   String q = "a b -c d e f";

   SolrQueryRequest req = req("q", q,
         DisMaxParams.QF, "f1 f2",
         DisMaxParams.MM, "3",
         QueryParsing.OP, "OR",
         DisMaxParams.PF, "f2^1.5 f3^1.5",
         DisMaxParams.PF2, "f1^2.1 f2^2.1",
         DisMaxParams.PF3, "f3^3.9 f1^3.9"
         );

   verifyQueryString(req, q,
         "(f2:\"a b d e f\")^1.5", "(f3:\"a b d e f\")^1.5",
         "(f1:\"a b\" f1:\"b d\" f1:\"d e\" f1:\"e f\")^2.1",
         "(f2:\"a b\" f2:\"b d\" f2:\"d e\" f2:\"e f\")^2.1",
         "(f3:\"a b d\" f3:\"b d e\" f3:\"d e f\")^3.9",
         "(f1:\"a b d\" f1:\"b d e\" f1:\"d e f\")^3.9"

   );

}
 
Example 22
Source Project: solr-redis   Source File: TestRedisQParser.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAddTermsFromRedisOnZrangeCommandWithCustomRange() throws SyntaxError, IOException {
  when(localParamsMock.get("command")).thenReturn("zrange");
  when(localParamsMock.get("key")).thenReturn("simpleKey");
  when(localParamsMock.get("range_start")).thenReturn("1");
  when(localParamsMock.get("range_end")).thenReturn("100");
  when(localParamsMock.get(QueryParsing.V)).thenReturn("string_field");
  when(jedisMock.zrangeWithScores(anyString(), anyLong(), anyLong()))
      .thenReturn(new HashSet<>(Arrays.asList(new Tuple("123", (double) 1.0f), new Tuple("321", (double) 1.0f))));
  when(requestMock.getSchema()).thenReturn(schema);
  when(schema.getQueryAnalyzer()).thenReturn(new StandardAnalyzer());
  redisQParser = new RedisQParser("string_field", localParamsMock, paramsMock, requestMock, commandHandler);
  final Query query = redisQParser.parse();
  verify(jedisMock).zrangeWithScores("simpleKey", 1, 100);
  IndexSearcher searcher = new IndexSearcher(new MultiReader());
  final Set<Term> terms = extractTerms(searcher, query);
  Assert.assertEquals(2, terms.size());
}
 
Example 23
Source Project: querqy   Source File: MainQueryBoostTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testIDFIsOnlyUsedInBoostQueryAndNotInUserQueryIfSimilarityIsOff() {
    String q = "qup";

    SolrQueryRequest req = req("q", q,
            DisMaxParams.QF, "f1^10 f2^2",
            QueryParsing.OP, "OR",
            USER_QUERY_SIMILARITY_SCORE, SIMILARITY_SCORE_OFF,
            "defType", "querqy",
            "debugQuery", "true"
    );

    assertQ("uq.similarityScore=off failed",
            req,
            "//result[@name='response'][@numFound='2']",
            "//str[@name='1'][not(contains(.,'idf'))]",  // no idf for user query
            "//str[@name='2'][not(contains(.,'idf'))]",  // no idf for user query
            // boost query score not ending in .0, indicating that similarity was used
            "//str[@name='2'][not(substring(.,string-length(.) - 2) = '0)')]");

    req.close();
}
 
Example 24
Source Project: solr-redis   Source File: TestRedisQParser.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldParseJsonTermsFromRedisOnGetCommand() throws SyntaxError, IOException {
  when(localParamsMock.get("command")).thenReturn("get");
  when(localParamsMock.get("key")).thenReturn("simpleKey");
  when(localParamsMock.get("serialization")).thenReturn("json");
  when(localParamsMock.get(QueryParsing.V)).thenReturn("string_field");
  when(jedisMock.get(any(byte[].class))).thenReturn("[1,2,3]".getBytes());
  when(requestMock.getSchema()).thenReturn(schema);
  when(schema.getQueryAnalyzer()).thenReturn(new StandardAnalyzer());
  redisQParser = new RedisQParser("string_field", localParamsMock, paramsMock, requestMock, commandHandler);
  final Query query = redisQParser.parse();
  verify(jedisMock).get("simpleKey".getBytes());
  IndexSearcher searcher = new IndexSearcher(new MultiReader());
  final Set<Term> terms = extractTerms(searcher, query);
  Assert.assertEquals(3, terms.size());
}
 
Example 25
Source Project: solr-redis   Source File: TestRedisQParser.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAddTermsFromSortOrderAsc() throws SyntaxError, IOException {
  when(localParamsMock.get("command")).thenReturn("sort");
  when(localParamsMock.get("key")).thenReturn("simpleKey");
  when(localParamsMock.get("order")).thenReturn("asc");
  when(localParamsMock.get(QueryParsing.V)).thenReturn("string_field");
  when(jedisMock.sort(anyString(), any(SortingParams.class))).thenReturn(Arrays.asList("123", "321"));
  when(requestMock.getSchema()).thenReturn(schema);
  when(schema.getQueryAnalyzer()).thenReturn(new StandardAnalyzer());
  redisQParser = new RedisQParser("string_field", localParamsMock, paramsMock, requestMock, commandHandler);
  final Query query = redisQParser.parse();
  final ArgumentCaptor<SortingParams> argument = ArgumentCaptor.forClass(SortingParams.class);
  verify(jedisMock).sort(eq("simpleKey"), argument.capture());
  Assert.assertEquals(getSortingParamString(new SortingParams().asc()), getSortingParamString(argument.getValue()));
  IndexSearcher searcher = new IndexSearcher(new MultiReader());
  final Set<Term> terms = extractTerms(searcher, query);
  Assert.assertEquals(2, terms.size());
}
 
Example 26
Source Project: BioSolr   Source File: XJoinQParserPlugin.java    License: Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Query parse() throws SyntaxError {
  Method method = Method.valueOf(localParams.get(METHOD, Method.termsFilter.name()));
  JoinSpec<T> js = JoinSpec.parse(localParams.get(QueryParsing.V));
  Iterator<T> it = js.iterator(this);
  if (joinField == null) {
    throw new Exception("No XJoin component referenced by query");
  }
  FieldType ft = req.getSchema().getFieldTypeNoEx(joinField);
  Iterator<BytesRef> bytesRefs = new TransformIterator(it, transformer(ft));
  if (! bytesRefs.hasNext()) {
    return new BooleanQuery.Builder().build(); // matches nothing
  }
  Query query = method.makeQuery(joinField, bytesRefs);
  return new SolrConstantScoreQuery(new QueryWrapperFilter(query));
}
 
Example 27
Source Project: solr-redis   Source File: TestRedisQParser.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAddTermsFromRedisOnEval() throws SyntaxError, IOException {
  when(localParamsMock.get("command")).thenReturn("eval");
  when(localParamsMock.get("script")).thenReturn("return 1;");
  when(localParamsMock.get("key")).thenReturn("k");
  when(localParamsMock.get("arg")).thenReturn("a");
  when(localParamsMock.getParameterNamesIterator())
      .thenReturn(
          Arrays.asList("command", "script", "key", "arg").iterator(),
          Arrays.asList("command", "script", "key", "arg").iterator());

  when(localParamsMock.get(QueryParsing.V)).thenReturn("string_field");
  when(jedisMock.eval(anyString(), anyInt(), (String) anyVararg())).thenReturn(1);

  when(requestMock.getSchema()).thenReturn(schema);
  when(schema.getQueryAnalyzer()).thenReturn(new StandardAnalyzer());
  redisQParser = new RedisQParser("string_field", localParamsMock, paramsMock, requestMock, commandHandler);
  final Query query = redisQParser.parse();
  verify(jedisMock).eval("return 1;", 1, "k", "a");
  IndexSearcher searcher = new IndexSearcher(new MultiReader());
  final Set<Term> terms = extractTerms(searcher, query);
  Assert.assertEquals(1, terms.size());
}
 
Example 28
Source Project: querqy   Source File: MainQueryBoostTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
    public void testThatNegBoostIsAppliedIfSimilarityIsDFC() {
        String q = "m u100";
//        m =>
//        DOWN(200000): d

        SolrQueryRequest req = req("q", q,
                DisMaxParams.QF, "f1^10 f2^2",
                QueryParsing.OP, "OR",
                USER_QUERY_SIMILARITY_SCORE, SIMILARITY_SCORE_DFC,
                USER_QUERY_BOOST, "80.0",
                QBOOST_NEG_WEIGHT, "3",
                "defType", "querqy",
                "debugQuery", "true"
        );

        assertQ("qboost.negWeight failed with uq.similarityScore=dfc",
                req,
                "//result[@name='response'][@numFound='2']",
                "//str[1][@name='2'][contains(.,'idf')]",
                "//str[1][@name='2'][contains(.,'600000.0 = FunctionQuery')]", // qboost.negWeight=3*DOWN(200000) added

                "//str[2][@name='3'][contains(.,'idf')]",
                "//str[2][@name='3'][not(contains(.,'60000.0 = FunctionQuery'))]");
        req.close();
    }
 
Example 29
Source Project: querqy   Source File: MainQueryBoostTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testThatNegBoostIsGradedIfSimilarityIsOff() {
    String q = "qdown1 qdown2";

    SolrQueryRequest req = req("q", q,
            DisMaxParams.QF, "f1",
            QueryParsing.OP, "OR",
            USER_QUERY_SIMILARITY_SCORE, SIMILARITY_SCORE_OFF,
            "defType", "querqy",
            "debugQuery", "true"
    );

    assertQ("graded down failed with uq.similarityScore=off",
            req,
            "//result[@name='response'][@numFound='2']",
            "//doc[1]/str[@name='id'][contains(.,'5')]",
            "//doc[2]/str[@name='id'][contains(.,'4')]",
            "//str[@name='5'][contains(.,'0.2 = AdditiveBoostFunction(-0.2,query(+f1:d2,def=0.0)=0.0)')]",
            "//str[@name='5'][contains(.,'AdditiveBoostFunction(-0.1,query(+f1:d1,def=0.0)')]",
            "//str[@name='5'][not(contains(.,'AdditiveBoostFunction(-0.1,query(+f1:d1,def=0.0)=0.0'))]",
            "//str[@name='4'][contains(.,'AdditiveBoostFunction(-0.2,query(+f1:d2,def=0.0)')]",
            "//str[@name='4'][not(contains(.,'AdditiveBoostFunction(-0.2,query(+f1:d2,def=0.0)=0.0'))]",
            "//str[@name='4'][contains(.,'AdditiveBoostFunction(-0.1,query(+f1:d1,def=0.0)=0.0)')]"
    );
    req.close();
}
 
Example 30
Source Project: querqy   Source File: MainQueryBoostTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testThatNegBoostIsGradedIfSimilarityIsOn() {
    String q = "qdown1 qdown2";

    SolrQueryRequest req = req("q", q,
            DisMaxParams.QF, "f1",
            QueryParsing.OP, "OR",
            USER_QUERY_SIMILARITY_SCORE, SIMILARITY_SCORE_ON,
            "defType", "querqy",
            "debugQuery", "true"
    );

    assertQ("graded down failed with uq.similarityScore=off",
            req,
            "//result[@name='response'][@numFound='2']",
            "//doc[1]/str[@name='id'][contains(.,'5')]",
            "//doc[2]/str[@name='id'][contains(.,'4')]",
            "//str[@name='5'][contains(.,'0.2 = AdditiveBoostFunction(-0.2,query(+f1:d2,def=0.0)=0.0)')]",
            "//str[@name='5'][contains(.,'AdditiveBoostFunction(-0.1,query(+f1:d1,def=0.0)')]",
            "//str[@name='5'][not(contains(.,'AdditiveBoostFunction(-0.1,query(+f1:d1,def=0.0)=0.0'))]",
            "//str[@name='4'][contains(.,'AdditiveBoostFunction(-0.2,query(+f1:d2,def=0.0)')]",
            "//str[@name='4'][not(contains(.,'AdditiveBoostFunction(-0.2,query(+f1:d2,def=0.0)=0.0'))]",
            "//str[@name='4'][contains(.,'0.1 = AdditiveBoostFunction(-0.1,query(+f1:d1,def=0.0)=0.0)')]"
    );
    req.close();
}