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

The following examples show how to use org.apache.solr.common.params.CommonParams. 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: lucene-solr   Source File: TestSolrEntityProcessorUnit.java    License: Apache License 2.0 6 votes vote down vote up
public void testPagingQuery() {
  SolrEntityProcessor processor = new NoNextMockProcessor() ;
  
  HashMap<String,String> entityAttrs = new HashMap<String,String>(){{
    put(SolrEntityProcessor.SOLR_SERVER,"http://route:66/no");
    if (random().nextBoolean()) {
      List<String> noCursor = Arrays.asList("","false",CursorMarkParams.CURSOR_MARK_START);//only 'true' not '*'
      Collections.shuffle(noCursor, random());
      put(CursorMarkParams.CURSOR_MARK_PARAM,  noCursor.get(0));
    }}};
  processor.init(getContext(null, null, null, null, Collections.emptyList(), 
      entityAttrs));
  try {
  processor.buildIterator();
  SolrQuery query = new SolrQuery();
  ((SolrDocumentListIterator) processor.rowIterator).passNextPage(query);
  assertEquals("0", query.get(CommonParams.START));
  assertNull( query.get(CursorMarkParams.CURSOR_MARK_PARAM));
  assertNotNull( query.get(CommonParams.TIME_ALLOWED));
  }finally {
    processor.destroy();
  }
}
 
Example 2
Source Project: lucene-solr   Source File: TestZKPropertiesWriter.java    License: 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 3
Source Project: vind   Source File: IssueExampleTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tests MBC-1203 (Static synonyms)
 * Attention! To enable this, make sure that you use the WhiteSpaceTokenizer (for query and index).
 */
@Test
@Ignore //At the moment synonyms are not supported in suggestions
public void testSynonymes() {

    ModifiableSolrParams params = new ModifiableSolrParams();

    params.add(SuggestionRequestParams.SUGGESTION, "true");
    params.add(CommonParams.QT,"/suggester");
    params.add(CommonParams.Q, "xalps");
    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 - test synonym mapping for single facet",req,
            "//response/lst[@name='suggestions']/int[@name='suggestion_count'][.='2']",
            "//response/lst[@name='suggestions']/lst[@name='suggestion_facets']/lst[@name='dynamic_multi_stored_suggest_analyzed_name']/int[@name='X-Alps'][.='1']",
            "//response/lst[@name='suggestions']/lst[@name='suggestion_facets']/lst[@name='dynamic_multi_stored_suggest_analyzed_name']/int[@name='My xa'][.='1']");
}
 
Example 4
Source Project: querqy   Source File: QuerqyDismaxQParserTest.java    License: 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 Project: vind   Source File: IssueExampleTest.java    License: 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 6
Source Project: lucene-solr   Source File: CopyFieldTest.java    License: 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 7
Source Project: vind   Source File: SuggestionRequestHandlerTest.java    License: 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 8
Source Project: vind   Source File: SuggestionRequestHandlerTest.java    License: 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 9
Source Project: vind   Source File: SuggestionRequestHandlerTest.java    License: 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 10
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 11
Source Project: lucene-solr   Source File: QParser.java    License: 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 12
@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 13
Source Project: incubator-retired-blur   Source File: BlurQueryHelper.java    License: 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 14
@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 15
Source Project: scipio-erp   Source File: SolrProductSearch.java    License: 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 16
Source Project: lucene-solr   Source File: LRUStatsCache.java    License: 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 17
Source Project: mycore   Source File: MCROAISolrSearcher.java    License: 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 18
Source Project: mycore   Source File: MCROAISolrSearcher.java    License: 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 19
Source Project: solr-autocomplete   Source File: DictionaryGroupingSort.java    License: 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 20
@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 21
Source Project: lucene-solr   Source File: SimCloudManager.java    License: 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 22
Source Project: solr-researcher   Source File: TestDymReSearcher.java    License: 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 23
Source Project: lucene-solr   Source File: BasicFunctionalityTest.java    License: 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 24
@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 25
@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 26
Source Project: lucene-solr   Source File: IndexFetcher.java    License: 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 27
@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 28
Source Project: lucene-solr   Source File: TestSpellCheckResponse.java    License: 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 29
Source Project: lucene-solr   Source File: LukeRequest.java    License: 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 30
Source Project: lucene-solr   Source File: MoreLikeThisComponentTest.java    License: 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();
}