org.apache.solr.common.params.CommonParams Java Examples

The following examples show how to use org.apache.solr.common.params.CommonParams. 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 File: MCROAISolrSearcher.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Optional<Instant> getEarliestTimestamp() {
    String sortBy = MCRConfiguration2.getString(getConfigPrefix() + "EarliestDatestamp.SortBy")
        .orElse("modified asc");
    String fieldName = MCRConfiguration2.getString(getConfigPrefix() + "EarliestDatestamp.FieldName")
        .orElse("modified");
    String restriction = MCRConfiguration2.getString(getConfigPrefix() + "Search.Restriction").orElse(null);
    ModifiableSolrParams params = new ModifiableSolrParams();
    params.add(CommonParams.SORT, sortBy);
    params.add(CommonParams.Q, restriction);
    params.add(CommonParams.FQ, fieldName + ":[* TO *]");
    params.add(CommonParams.FL, fieldName);
    params.add(CommonParams.ROWS, "1");
    SolrClient solrClient = MCRSolrClientFactory.getMainSolrClient();
    try {
        QueryResponse response = solrClient.query(params);
        SolrDocumentList list = response.getResults();
        if (list.size() >= 1) {
            Date date = (Date) list.get(0).getFieldValue(fieldName);
            return Optional.of(date.toInstant());
        }
    } catch (Exception exc) {
        LOGGER.error("Unable to handle solr request", exc);
    }
    return Optional.empty();
}
 
Example #2
Source File: SuggestionRequestHandlerTest.java    From vind with Apache License 2.0 6 votes vote down vote up
@Test
public void spellcheckSuggestionTest() {

    ModifiableSolrParams params = new ModifiableSolrParams();

    params.add(SuggestionRequestParams.SUGGESTION,"true");
    params.add(CommonParams.QT,"/suggester");
    params.add(CommonParams.Q,"sepastian");
    params.add(SuggestionRequestParams.SUGGESTION_FIELD,"dynamic_multi_stored_suggest_analyzed_name");
    params.add(SuggestionRequestParams.SUGGESTION_DF,"suggestions");

    SolrQueryRequest req = new LocalSolrQueryRequest( core, params );

    assertQ("suggester - spellcheck suggestion for 'sepastian'",req,
            "//response/lst[@name='suggestions']/int[@name='suggestion_count'][.='1']",
            "//response/lst[@name='suggestions']/lst[@name='suggestion_facets']/lst[@name='dynamic_multi_stored_suggest_analyzed_name']/int[@name='sebastian vettel'][.='2']",
            "//response/lst[@name='spellcheck']/lst[@name='collations']/str[@name='collation'][.='sebastian']");

}
 
Example #3
Source File: SuggestionRequestHandlerTest.java    From vind with Apache License 2.0 6 votes vote down vote up
@Test
public void fqParameterTest() {

    ModifiableSolrParams params = new ModifiableSolrParams();

    params.add(SuggestionRequestParams.SUGGESTION,"true");
    params.add(CommonParams.QT,"/suggester");
    params.add(CommonParams.Q,"sebastian");
    params.add(SuggestionRequestParams.SUGGESTION_FIELD,"dynamic_multi_stored_suggest_analyzed_name");
    params.add(CommonParams.FQ,"dynamic_multi_stored_suggest_analyzed_place:\"(1328869589310-619798898)\"");

    SolrQueryRequest req = new LocalSolrQueryRequest( core, params );

    assertQ("suggester - spellcheck suggestion for 'sepastian'",req,
            "//response/lst[@name='suggestions']/int[@name='suggestion_count'][.='1']",
            "//response/lst[@name='suggestions']/lst[@name='suggestion_facets']/lst[@name='dynamic_multi_stored_suggest_analyzed_name']/int[@name='sebastian vettel'][.='1']");

}
 
Example #4
Source File: QuerqyDismaxQParserTest.java    From querqy with Apache License 2.0 6 votes vote down vote up
@Test
public void testThatInterdependentLuceneQueriesWillNotBeCachedSeparately() throws Exception {

    when(request.getSchema()).thenReturn(schema);
    when(schema.getQueryAnalyzer()).thenReturn(new StandardAnalyzer());
    when(rewriteChain.rewrite(any(), any())).thenReturn(new ExpandedQuery(new MatchAllQuery()));

    final ModifiableSolrParams solrParams = new ModifiableSolrParams();
    solrParams.add("qf", "f1");

    final ModifiableSolrParams localParams = new ModifiableSolrParams();
    localParams.add(CommonParams.CACHE, "sep");

    final QuerqyDismaxQParser parser = new QuerqyDismaxQParser("*:*", localParams, solrParams, request,
            querqyParser, rewriteChain, infoLogging, null);
    parser.luceneQueries = new LuceneQueries(new MatchAllDocsQuery(), Collections.emptyList(),
            Collections.singletonList(new MatchAllDocsQuery()), new MatchAllDocsQuery(), true);
    parser.applyLocalParams();

    final Query query = parser.getQuery();
    Assert.assertFalse(query instanceof ExtendedQuery);
}
 
Example #5
Source File: CopyFieldTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Test
public void testSourceGlobMatchesNoDynamicOrExplicitField()
{
  // SOLR-4650: copyField source globs should not have to match an explicit or dynamic field 
  SolrCore core = h.getCore();
  IndexSchema schema = core.getLatestSchema();

  assertNull("'testing123_*' should not be (or match) a dynamic or explicit field", schema.getFieldOrNull("testing123_*"));

  assertTrue("schema should contain dynamic field '*_s'", schema.getDynamicPattern("*_s").equals("*_s"));

  assertU(adoc("id", "5", "sku1", "10-1839ACX-93", "testing123_s", "AAM46"));
  assertU(commit());

  Map<String,String> args = new HashMap<>();
  args.put( CommonParams.Q, "text:AAM46" );
  args.put( "indent", "true" );
  SolrQueryRequest req = new LocalSolrQueryRequest( core, new MapSolrParams( args) );
  assertQ("sku2 copied to text", req
      ,"//*[@numFound='1']"
      ,"//result/doc[1]/str[@name='id'][.='5']"
  );
}
 
Example #6
Source File: IssueExampleTest.java    From vind with Apache License 2.0 6 votes vote down vote up
@Test
public void test_PSD_3756() {

    ModifiableSolrParams params = new ModifiableSolrParams();

    params.add(SuggestionRequestParams.SUGGESTION,"true");
    params.add(CommonParams.QT,"/suggester");
    params.add(CommonParams.Q,"The Real Dingo");
    params.add(SuggestionRequestParams.SUGGESTION_FIELD,"dynamic_multi_stored_suggest_analyzed_source");
    params.add(SuggestionRequestParams.SUGGESTION_DF,"suggestions");

    SolrQueryRequest req = new LocalSolrQueryRequest( core, params );

    assertQ("suggester - test path hierarchy", req,
            "//response/lst[@name='suggestions']/int[@name='suggestion_count'][.='1']",
            "//response/lst[@name='suggestions']/lst[@name='suggestion_facets']/lst[@name='dynamic_multi_stored_suggest_analyzed_source']/int[@name='The Real Dingo'][.='1']");

}
 
Example #7
Source File: SuggestionRequestHandlerTest.java    From vind with Apache License 2.0 6 votes vote down vote up
@Test
public void sortingTest2() {
    ModifiableSolrParams params = new ModifiableSolrParams();

    params.add(SuggestionRequestParams.SUGGESTION,"true");
    params.add(CommonParams.QT,"/suggester");
    params.add(CommonParams.Q,"ku");
    params.add(SuggestionRequestParams.SUGGESTION_FIELD,"dynamic_multi_stored_suggest_analyzed_place");

    SolrQueryRequest req = new LocalSolrQueryRequest( core, params );

    assertQ("suggester - test single sorting for 'ku' with 2 facets", req,
            "//response/lst[@name='suggestions']/lst[@name='suggestion_facets']/lst[@name='dynamic_multi_stored_suggest_analyzed_place']/int[@name='kuala Lumpur'][.='2']",
            "//response/lst[@name='suggestions']/lst[@name='suggestion_facets']/lst[@name='dynamic_multi_stored_suggest_analyzed_place']/int[1][.='2']",
            "//response/lst[@name='suggestions']/lst[@name='suggestion_facets']/lst[@name='dynamic_multi_stored_suggest_analyzed_place']/int[@name='Havanna kuba'][.='1']");
}
 
Example #8
Source File: AlfrescoReRankQParserPlugin.java    From SearchServices with GNU Lesser General Public License v3.0 6 votes vote down vote up
public Query parse() throws SyntaxError {
    String reRankQueryString = localParams.get("reRankQuery");
    boolean scale = localParams.getBool("scale", false);
    QParser reRankParser = QParser.getParser(reRankQueryString, null, req);
    Query reRankQuery = reRankParser.parse();

    int reRankDocs  = localParams.getInt("reRankDocs", 200);
    reRankDocs = Math.max(1, reRankDocs); //

    double reRankWeight = localParams.getDouble("reRankWeight",2.0d);

    int start = params.getInt(CommonParams.START,0);
    int rows = params.getInt(CommonParams.ROWS,10);
    int length = start+rows;
    return new ReRankQuery(reRankQuery, reRankDocs, reRankWeight, length, scale);
}
 
Example #9
Source File: QParser.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the resulting query from this QParser, calling parse() only the
 * first time and caching the Query result. <em>A null return is possible!</em>
 */
//TODO never return null; standardize the semantics
public Query getQuery() throws SyntaxError {
  if (query==null) {
    query=parse();

    if (localParams != null) {
      String cacheStr = localParams.get(CommonParams.CACHE);
      if (cacheStr != null) {
        if (CommonParams.FALSE.equals(cacheStr)) {
          extendedQuery().setCache(false);
        } else if (CommonParams.TRUE.equals(cacheStr)) {
          extendedQuery().setCache(true);
        } else if ("sep".equals(cacheStr)) {
          extendedQuery().setCacheSep(true);
        }
      }

      int cost = localParams.getInt(CommonParams.COST, Integer.MIN_VALUE);
      if (cost != Integer.MIN_VALUE) {
        extendedQuery().setCost(cost);
      }
    }
  }
  return query;
}
 
Example #10
Source File: SolrInformationServerTest.java    From SearchServices with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testGetStateOk()
{
    String id = String.valueOf(System.currentTimeMillis());

    SolrDocument state = new SolrDocument();

    SimpleOrderedMap<SolrDocument> responseContent = new SimpleOrderedMap<>();
    responseContent.add(SolrInformationServer.RESPONSE_DEFAULT_ID, state);

    when(response.getValues()).thenReturn(responseContent);
    when(core.getRequestHandler(SolrInformationServer.REQUEST_HANDLER_GET)).thenReturn(handler);

    SolrDocument document = infoServer.getState(core, request, id);

    assertEquals(id, request.getParams().get(CommonParams.ID));
    verify(core).getRequestHandler(SolrInformationServer.REQUEST_HANDLER_GET);
    verify(response).getValues();

    assertSame(state, document);
}
 
Example #11
Source File: BlurQueryHelper.java    From incubator-retired-blur with Apache License 2.0 6 votes vote down vote up
private static void maybeAddSelector(BlurQuery blurQuery, SolrParams p) {
  String fieldString = p.get(CommonParams.FL);
  Selector selector = new Selector();
  selector.setRecordOnly(true);

  if (fieldString != null) {
    Map<String, Set<String>> famCols = Maps.newHashMap();
    String[] fields = fieldString.split(",");

    for (String field : fields) {
      String[] famCol = field.split("\\.");

      if (famCol.length != 2) {
        throw new IllegalArgumentException("Fields must be in a family.column format[" + field + "]");
      }
      if (!famCols.containsKey(famCol[0])) {
        famCols.put(famCol[0], new HashSet<String>());
      }
      Set<String> cols = famCols.get(famCol[0]);
      cols.add(famCol[1]);
    }
    selector.setColumnsToFetch(famCols);

  }
  blurQuery.setSelector(selector);
}
 
Example #12
Source File: QueryAutoFilteringComponentTest.java    From query-autofiltering-component with Apache License 2.0 6 votes vote down vote up
@Test
public void testMinTokens( ) {
  System.out.println( "testMinTokens" );
  clearIndex();
  assertU(commit());
  assertU(adoc("id", "1", "color", "red",   "product", "shoes" ));
  assertU(adoc("id", "2", "color", "red",   "product", "socks" ));
  assertU(adoc("id", "3", "color", "green", "brand", "red lion",  "product", "socks"));
  assertU(adoc("id", "4", "brand", "red label",  "product", "whiskey"));
  assertU(commit());
    
  assertQ("", req(CommonParams.Q, "red", CommonParams.QT, "/autofilter" )
          , "//*[@numFound='2']"
          , "//doc[./str[@name='id']='1']"
          , "//doc[./str[@name='id']='2']" );

  assertQ("", req(CommonParams.Q, "red", CommonParams.QT, "/autofilter", "mt", "2" )
            , "//*[@numFound='4']" );
    
  assertQ("", req(CommonParams.Q, "red shoes", CommonParams.QT, "/autofilter", "mt", "2" )
            , "//*[@numFound='1']"
            , "//doc[./str[@name='id']='1']" );
}
 
Example #13
Source File: SolrProductSearch.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
public static Map<String, Object> reloadSolrSecurityAuthorizations(DispatchContext dctx, Map<String, Object> context) {
    if (!SolrUtil.isSystemInitialized()) { // NOTE: this must NOT use SolrUtil.isSolrLocalWebappPresent() anymore
        return ServiceUtil.returnFailure("Solr not enabled or system not ready");
    }
    try {
        HttpSolrClient client = SolrUtil.getAdminHttpSolrClientFromUrl(SolrUtil.getSolrWebappUrl());
        //ModifiableSolrParams params = new ModifiableSolrParams();
        //// this is very sketchy, I don't think ModifiableSolrParams were meant for this
        //params.set("set-user-role", (String) null);
        //SolrRequest<?> request = new GenericSolrRequest(METHOD.POST, CommonParams.AUTHZ_PATH, params);
        SolrRequest<?> request = new DirectJsonRequest(CommonParams.AUTHZ_PATH,
                "{\"set-user-role\":{}}"); // "{\"set-user-role\":{\"dummy\":\"dummy\"}}"
        client.request(request);
        Debug.logInfo("Solr: reloadSolrSecurityAuthorizations: invoked reload", module);
        return ServiceUtil.returnSuccess();
    } catch (Exception e) {
        Debug.logError("Solr: reloadSolrSecurityAuthorizations: error: " + e.getMessage(), module);
        return ServiceUtil.returnError("Error reloading Solr security authorizations: " + e.getMessage());
    }
}
 
Example #14
Source File: LRUStatsCache.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
protected void addToPerShardTermStats(SolrQueryRequest req, String shard, String termStatsString) {
  Map<String,TermStats> termStats = StatsUtil.termStatsMapFromString(termStatsString);
  if (termStats != null) {
    @SuppressWarnings({"unchecked"})
    SolrCache<String,TermStats> cache = perShardTermStats.computeIfAbsent(shard, s -> {
      @SuppressWarnings({"rawtypes"})
      CaffeineCache c = new CaffeineCache<>();
      Map<String, String> map = new HashMap<>(lruCacheInitArgs);
      map.put(CommonParams.NAME, s);
      c.init(map, null, null);
      c.setState(SolrCache.State.LIVE);
      return c;
    });
    for (Entry<String,TermStats> e : termStats.entrySet()) {
      cache.put(e.getKey(), e.getValue());
    }
  }
}
 
Example #15
Source File: MCROAISolrSearcher.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
protected MCROAISolrResult solrQuery(Optional<String> cursor) throws SolrServerException, IOException {
    SolrQuery query = getBaseQuery(CommonParams.Q);

    // set support
    if (this.set != null) {
        String setId = this.set.getSetId();
        MCROAISetConfiguration<SolrQuery, SolrDocument, String> setConfig = getSetManager().getConfig(setId);
        setConfig.getHandler().apply(this.set, query);
    }
    // from & until
    if (this.from != null || this.until != null) {
        String fromUntilCondition = buildFromUntilCondition(this.from, this.until);
        query.add(CommonParams.FQ, fromUntilCondition);
    }

    // cursor
    query.set(CursorMarkParams.CURSOR_MARK_PARAM, cursor.orElse(CursorMarkParams.CURSOR_MARK_START));
    query.set(CommonParams.ROWS, String.valueOf(getPartitionSize()));
    query.set(CommonParams.SORT, "id asc");

    // do the query
    SolrClient solrClient = MCRSolrClientFactory.getMainSolrClient();
    QueryResponse response = solrClient.query(query);
    Collection<MCROAISetResolver<String, SolrDocument>> setResolver = getSetResolver(response.getResults());
    return new MCROAISolrResult(response, d -> toHeader(d, setResolver));
}
 
Example #16
Source File: TestZKPropertiesWriter.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * Code copied with some adaptations from {@link org.apache.solr.util.TestHarness.LocalRequestFactory#makeRequest(String...)}.
 */
@SuppressWarnings({"unchecked"})
private static LocalSolrQueryRequest localMakeRequest(SolrCore core, String ... q) {
  if (q.length==1) {
    Map<String, String> args = new HashMap<>();
    args.put(CommonParams.VERSION,"2.2");

    return new LocalSolrQueryRequest(core, q[0], "", 0, 20, args);
  }
  if (q.length%2 != 0) {
    throw new RuntimeException("The length of the string array (query arguments) needs to be even");
  }
  @SuppressWarnings({"rawtypes"})
  Map.Entry<String, String> [] entries = new NamedList.NamedListEntry[q.length / 2];
  for (int i = 0; i < q.length; i += 2) {
    entries[i/2] = new NamedList.NamedListEntry<>(q[i], q[i+1]);
  }
  @SuppressWarnings({"rawtypes"})
  NamedList nl = new NamedList(entries);
  if(nl.get("wt" ) == null) nl.add("wt","xml");
  return new LocalSolrQueryRequest(core, nl);
}
 
Example #17
Source File: DictionaryGroupingSort.java    From solr-autocomplete with Apache License 2.0 6 votes vote down vote up
@Override
public void sort(ResponseBuilder rb, List<AcGroupResult> allGroupsResults) {

  // Look if some words of the query is in a dictionary
  String q = rb.req.getParams().get(CommonParams.Q);
  List<TypedSegment> segments = segmenter.segment(q);

  // No words from the query in any dictionary. Just keep the original ordering of groups.
  if (segments.isEmpty()) {
    return;
  }

  // TODO for now, we only elevate the first group that matches, but we might need to do the same for the others.
  TypedSegment typedSegment = segments.get(0);

  // The dictionary name is the group name
  String groupNameToElevate = typedSegment.getDictionaryName();

  // Check if a group with the same name is there. If it's the case, remove it from list (temporarily).
  AcGroupResult groupToElavate = removeMatchingGroup(allGroupsResults, groupNameToElevate);

  // Put back group at the top of the list
  if (groupToElavate != null) {
    allGroupsResults.add(0, groupToElavate);
  }
}
 
Example #18
Source File: QueryAutoFilteringComponentTest.java    From query-autofiltering-component with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultipleFieldValues( ) {
  clearIndex();
  assertU(commit());
  assertU(adoc("id", "1", "color", "red",   "product", "shoes" ));
  assertU(adoc("id", "2", "color", "red",   "product", "socks" ));
  assertU(adoc("id", "3", "color", "green", "brand", "red lion",  "product", "socks"));
  assertU(adoc("id", "4", "brand", "red label",  "product", "whiskey"));
  assertU(adoc("id", "5", "color", "blue",  "brand", "green dragon", "product", "socks"));
  assertU(commit());
    
  // should create filter  query: color:(red OR green) product:socks
  assertQ("", req(CommonParams.Q, "red green socks", CommonParams.QT, "/autofilter" )
            , "//*[@numFound='2']"
            , "//doc[./str[@name='id']='2']"
            , "//doc[./str[@name='id']='3']");
}
 
Example #19
Source File: SimCloudManager.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * Add a new node and initialize its node values (metrics). The
 * /live_nodes list is updated with the new node id.
 * @return new node id
 */
public String simAddNode() throws Exception {
  Map<String, Object> values = createNodeValues(null);
  String nodeId = (String)values.get(ImplicitSnitch.NODE);
  nodeStateProvider.simSetNodeValues(nodeId, values);
  clusterStateProvider.simAddNode(nodeId);
  log.trace("-- added node {}", nodeId);
  // initialize history handler if this is the first node
  if (metricsHistoryHandler == null && liveNodesSet.size() == 1) {
    metricsHandler = new MetricsHandler(metricManager);
    metricsHistoryHandler = new MetricsHistoryHandler(nodeId, metricsHandler, solrClient, this, new HashMap<>());
    SolrMetricsContext solrMetricsContext = new SolrMetricsContext(metricManager, SolrMetricManager.getRegistryName(SolrInfoBean.Group.node), metricTag);
    metricsHistoryHandler.initializeMetrics(solrMetricsContext, CommonParams.METRICS_HISTORY_PATH);
  }
  return nodeId;
}
 
Example #20
Source File: TestDymReSearcher.java    From solr-researcher with Apache License 2.0 6 votes vote down vote up
@Test
public void testSingleWord() {
  assertQ(req(CommonParams.QT, "standard", 
      CommonParams.Q, "foo:bon",
      SpellingParams.SPELLCHECK_COLLATE, "true", 
      SpellingParams.SPELLCHECK_BUILD, "true", 
      SpellingParams.SPELLCHECK_COUNT, "10", 
      SpellingParams.SPELLCHECK_EXTENDED_RESULTS, "true",
      DymReSearcher.COMPONENT_NAME, "true",
      SpellCheckComponent.COMPONENT_NAME, "true")
      ,"//result[@name='spellchecked_response'][@numFound='8']"
      ,"//result[@name='response'][@numFound='0']"
      ,"//arr[@name='extended_spellchecker_suggestions']/str[1][.='foo:bob']"
      ,"//arr[@name='extended_spellchecker_suggestions']/str[2][.='foo:bono']"
      ,"//lst[@name='extended_spellchecker_suggestions_hit_counts']/long[@name='foo:bob'][.='8']"
      ,"//lst[@name='extended_spellchecker_suggestions_hit_counts']/long[@name='foo:bono'][.='4']"
      ,"//result[@name='spellchecked_response']/doc[1]/str[@name='id'][.='2']"
      ,"//result[@name='spellchecked_response']/doc[2]/str[@name='id'][.='3']"
      ,"//result[@name='spellchecked_response']/doc[3]/str[@name='id'][.='5']"
      ,"//result[@name='spellchecked_response']/doc[4]/str[@name='id'][.='7']"
      ,"//result[@name='spellchecked_response']/doc[5]/str[@name='id'][.='8']"
      ,"//result[@name='spellchecked_response']/doc[6]/str[@name='id'][.='9']"
      ,"//result[@name='spellchecked_response']/doc[7]/str[@name='id'][.='10']"
      ,"//result[@name='spellchecked_response']/doc[8]/str[@name='id'][.='11']");
}
 
Example #21
Source File: BasicFunctionalityTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Test
public void testFieldBoost() throws Exception {
  String res = h.update("<add>" + "<doc><field name=\"id\">1</field>"+
                                    "<field name=\"text\">hello</field></doc>" + 
                                  "<doc><field name=\"id\">2</field>" +
                                    "<field boost=\"2.0\" name=\"text\">hello</field></doc>" + 
                        "</add>");

  // assertEquals("<result status=\"0\"></result>", res);
  assertU("<commit/>");
  assertQ(req("text:hello"),
          "//*[@numFound='2']"
          );
  String resp = h.query(lrf.makeRequest("q", "text:hello", CommonParams.DEBUG_QUERY, "true"));
  //System.out.println(resp);
  // second doc ranked first
  assertTrue( resp.indexOf("\"2\"") < resp.indexOf("\"1\"") );
}
 
Example #22
Source File: QueryAutoFilteringComponentTest.java    From query-autofiltering-component with Apache License 2.0 6 votes vote down vote up
@Test
public void testSynonymsCaseInsensitive( ) {
  System.out.println( "testSynonymsCaseInsensitive" );
  clearIndex();
  assertU(commit());
  assertU(adoc("id", "1", "color", "red",   "product", "Chaise Lounge" ));
  assertU(adoc("id", "2", "color", "red",   "product", "sofa" ));
  assertU(adoc("id", "3", "color", "red",   "product", "chair" ));
  assertU(commit());
      
  assertQ("", req(CommonParams.Q, "red lounge chair", CommonParams.QT, "/autofilter" )
            , "//*[@numFound='1']"
            , "//doc[./str[@name='id']='1']" );
      
  assertQ("", req(CommonParams.Q, "scarlet Lounge Chair", CommonParams.QT, "/autofilter" )
            , "//*[@numFound='1']"
            , "//doc[./str[@name='id']='1']" );
    
  assertQ("", req(CommonParams.Q, "Crimson Couch", CommonParams.QT, "/autofilter" )
            , "//*[@numFound='1']"
            , "//doc[./str[@name='id']='2']" );
}
 
Example #23
Source File: AutoCompleteSearchComponentTest.java    From solr-autocomplete with Apache License 2.0 6 votes vote down vote up
@Test
public void testAcQuerySomeValueExistsMultipleTimes() {
  assertQ(req(CommonParams.QT, "dismax_ac",
      CommonParams.DF, "prefixTok",
      CommonParams.Q, "bo",
      AutoCompleteSearchComponent.AC_GROUPING_FIELD_PARAM_NAME, "is_sponsored",
      AutoCompleteSearchComponent.AC_GROUPING_FIELD_DEFINITION_PARAM_NAME, "false:3 true:1 false:2",
      AutoCompleteSearchComponent.COMPONENT_NAME, "true")
      ,"//result[@name='response'][@numFound='6']"
      ,"//result[@name='response']/doc[1]/bool[@name='is_sponsored'][.='false']"
      ,"//result[@name='response']/doc[2]/bool[@name='is_sponsored'][.='false']"
      ,"//result[@name='response']/doc[3]/bool[@name='is_sponsored'][.='false']"
      ,"//result[@name='response']/doc[4]/bool[@name='is_sponsored'][.='true']"
      ,"//result[@name='response']/doc[5]/bool[@name='is_sponsored'][.='false']"
      ,"//result[@name='response']/doc[6]/bool[@name='is_sponsored'][.='false']"
  );
}
 
Example #24
Source File: IndexFetcher.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"rawtypes"})
NamedList getDetails() throws IOException, SolrServerException {
  ModifiableSolrParams params = new ModifiableSolrParams();
  params.set(COMMAND, CMD_DETAILS);
  params.set("slave", false);
  params.set(CommonParams.QT, ReplicationHandler.PATH);

  // TODO use shardhandler
  try (HttpSolrClient client = new HttpSolrClient.Builder(masterUrl)
      .withHttpClient(myHttpClient)
      .withConnectionTimeout(connTimeout)
      .withSocketTimeout(soTimeout)
      .build()) {
    QueryRequest request = new QueryRequest(params);
    return client.request(request);
  }
}
 
Example #25
Source File: AutoCompleteSearchComponentTest.java    From solr-autocomplete with Apache License 2.0 6 votes vote down vote up
@Test
public void testAcBoostCorrectWordOrdering() {
  assertQ(req(CommonParams.QT, "dismax_ac",
      CommonParams.DF, "prefixTok",
      CommonParams.Q, "washington tim",
      AutoCompleteSearchComponent.COMPONENT_NAME, "true")
      ,"//result[@name='response'][@numFound='2']"
      ,"//result[@name='response']/doc[2]/str[@name='phrase'][.='the washington times article']"
      ,"//result[@name='response']/doc[1]/str[@name='phrase'][.='times in washington']"
  );
  assertQ(req(CommonParams.QT, "dismax_ac", 
      CommonParams.Q, "washington tim",
      AutoCompleteSearchComponent.AC_MATCH_CORRECT_WORD_ORDERING_PARAM_NAME, "true",
      AutoCompleteSearchComponent.COMPONENT_NAME, "true")
      ,"//result[@name='response'][@numFound='2']"
      ,"//result[@name='response']/doc[1]/str[@name='phrase'][.='the washington times article']"
      ,"//result[@name='response']/doc[2]/str[@name='phrase'][.='times in washington']"
  );
}
 
Example #26
Source File: TestSpellCheckResponse.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Test
public void testSpellCheckResponse() throws Exception {
  getSolrClient();
  client.deleteByQuery("*:*");
  client.commit(true, true);
  SolrInputDocument doc = new SolrInputDocument();
  doc.setField("id", "111");
  doc.setField(field, "Samsung");
  client.add(doc);
  client.commit(true, true);

  SolrQuery query = new SolrQuery("*:*");
  query.set(CommonParams.QT, "/spell");
  query.set("spellcheck", true);
  query.set(SpellingParams.SPELLCHECK_Q, "samsang");
  QueryRequest request = new QueryRequest(query);
  SpellCheckResponse response = request.process(client).getSpellCheckResponse();
  Assert.assertEquals("samsung", response.getFirstSuggestion("samsang"));
}
 
Example #27
Source File: LukeRequest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public SolrParams getParams() {
  ModifiableSolrParams params = new ModifiableSolrParams();
  if( fields != null && fields.size() > 0 ) {
    params.add( CommonParams.FL, fields.toArray( new String[fields.size()] ) );
  }
  if( numTerms >= 0 ) {
    params.add( "numTerms", numTerms+"" );
  }
  if (showSchema) {
    params.add("show", "schema");
  }
  if (includeIndexFieldFlags != null) {
    params.add("includeIndexFieldFlags", includeIndexFieldFlags.toString());
  }

  return params;
}
 
Example #28
Source File: MoreLikeThisComponentTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Test
public void testMLT_baseParamsInterestingTermsDetails_shouldReturnSimilarDocumentsAndInterestingTermsDetails()
{
  SolrCore core = h.getCore();
  ModifiableSolrParams params = new ModifiableSolrParams();

  initCommonMoreLikeThisParams(params);
  params.set(MoreLikeThisParams.INTERESTING_TERMS, "details");
  
  params.set(CommonParams.Q, "id:42");
  SolrQueryRequest mltreq = new LocalSolrQueryRequest( core, params);
  assertQ("morelikethis - tom cruise",mltreq
      ,"//result/doc[1]/str[@name='id'][.='46']"
      ,"//result/doc[2]/str[@name='id'][.='43']",
      "//lst[@name='interestingTerms']/lst[1][count(*)>0]",
      "//lst[@name='interestingTerms']/lst[1]/float[.=1.0]");
  mltreq.close();
}
 
Example #29
Source File: CdcrRequestHandler.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public Long call() throws Exception {
  try (HttpSolrClient server = new HttpSolrClient.Builder(baseUrl)
      .withConnectionTimeout(15000)
      .withSocketTimeout(60000)
      .build()) {

    ModifiableSolrParams params = new ModifiableSolrParams();
    params.set(CommonParams.ACTION, CdcrParams.CdcrAction.SHARDCHECKPOINT.toString());

    @SuppressWarnings({"rawtypes"})
    SolrRequest request = new QueryRequest(params);
    request.setPath(cdcrPath);

    @SuppressWarnings({"rawtypes"})
    NamedList response = server.request(request);
    return (Long) response.get(CdcrParams.CHECKPOINT);
  }
}
 
Example #30
Source File: ReplicationHandler.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * This method adds an Object of FileStream to the response . The FileStream implements a custom protocol which is
 * understood by IndexFetcher.FileFetcher
 *
 * @see IndexFetcher.LocalFsFileFetcher
 * @see IndexFetcher.DirectoryFileFetcher
 */
private void getFileStream(SolrParams solrParams, SolrQueryResponse rsp) {
  ModifiableSolrParams rawParams = new ModifiableSolrParams(solrParams);
  rawParams.set(CommonParams.WT, FILE_STREAM);

  String cfileName = solrParams.get(CONF_FILE_SHORT);
  String tlogFileName = solrParams.get(TLOG_FILE);
  if (cfileName != null) {
    rsp.add(FILE_STREAM, new LocalFsConfFileStream(solrParams));
  } else if (tlogFileName != null) {
    rsp.add(FILE_STREAM, new LocalFsTlogFileStream(solrParams));
  } else {
    rsp.add(FILE_STREAM, new DirectoryFileStream(solrParams));
  }
  rsp.add(STATUS, OK_STATUS);
}