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

The following examples show how to use org.apache.solr.common.params.ModifiableSolrParams. 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: TestCollectionAPI.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
private void listCollection() throws IOException, SolrServerException {
  try (CloudSolrClient client = createCloudClient(null)) {
    ModifiableSolrParams params = new ModifiableSolrParams();
    params.set("action", CollectionParams.CollectionAction.LIST.toString());
    @SuppressWarnings({"rawtypes"})
    SolrRequest request = new QueryRequest(params);
    request.setPath("/admin/collections");

    NamedList<Object> rsp = client.request(request);
    @SuppressWarnings({"unchecked"})
    List<String> collections = (List<String>) rsp.get("collections");
    assertTrue("control_collection was not found in list", collections.contains("control_collection"));
    assertTrue(DEFAULT_COLLECTION + " was not found in list", collections.contains(DEFAULT_COLLECTION));
    assertTrue(COLLECTION_NAME + " was not found in list", collections.contains(COLLECTION_NAME));
    assertTrue(COLLECTION_NAME1 + " was not found in list", collections.contains(COLLECTION_NAME1));
  }

}
 
Example #2
Source File: IssueExampleTest.java    From vind with 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 #3
Source File: TestRedisQParserPluginIT.java    From solr-redis with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRetryOnConnectionProblem() {
  final String[] doc = {"id", "1", "string_field", "test"};
  assertU(adoc(doc));
  assertU(commit());

  final ModifiableSolrParams params = new ModifiableSolrParams();
  params.add("q", "*:*");
  params.add("fq", "{!redis command=smembers key=test_set}string_field");
  assertQ(req(params), "*[count(//doc)=1]", "//result/doc[1]/str[@name='id'][.='1']");

  jedis.configSet("timeout", "1");
  try {
    TimeUnit.SECONDS.sleep(2);
  } catch (final InterruptedException e) {
    Thread.currentThread().interrupt();
  }

  assertQ(req(params), "*[count(//doc)=1]", "//result/doc[1]/str[@name='id'][.='1']");
}
 
Example #4
Source File: TestTaggedQueryHighlighterIT.java    From solr-redis with Apache License 2.0 6 votes vote down vote up
@Test
public void testHighlightNoDuplicates() {
  final String[] doc1 = {"id", "1", "string_field", "test1"};
  assertU(adoc(doc1));
  assertU(commit());

  ModifiableSolrParams params = new ModifiableSolrParams();
  params.add("q", "({!redis command=smembers key=test_set1 v=string_field tag=test_tag1})"
          + " OR ({!redis command=smembers key=test_set1 v=string_field tag=test_tag1})");
  params.add("hl", "true");
  params.add("hl.fl", "test_tag1");
  assertQ(req(params),
          "*[count(//doc)=1]",
          "count(//lst[@name='highlighting']/*)=1",
          "//lst[@name='highlighting']/lst[@name='1']/arr[@name='test_tag1']/str='<em>test1</em>'");
}
 
Example #5
Source File: TestRedisQParserPluginIT.java    From solr-redis with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldFindThreeDocumentsSmembers() {
  final String[] doc1 = {"id", "1", "string_field", "test"};
  final String[] doc2 = {"id", "2", "string_field", "other_key"};
  final String[] doc3 = {"id", "3", "string_field", "other_key"};
  assertU(adoc(doc1));
  assertU(adoc(doc2));
  assertU(adoc(doc3));
  assertU(commit());

  jedis.sadd("test_set", "other_key");

  final ModifiableSolrParams params = new ModifiableSolrParams();
  params.add("q", "*:*");
  params.add("fq", "{!redis command=smembers key=test_set}string_field");
  params.add("sort", "id asc");
  assertQ(req(params), "*[count(//doc)=3]", "//result/doc[1]/str[@name='id'][.='1']",
      "//result/doc[2]/str[@name='id'][.='2']", "//result/doc[3]/str[@name='id'][.='3']");
}
 
Example #6
Source File: RoutedAliasUpdateProcessor.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public void processAdd(AddUpdateCommand cmd) throws IOException {
  routedAlias.validateRouteValue(cmd);

  // to avoid potential for race conditions, this next method should not get called again unless
  // we have created a collection synchronously
  routedAlias.updateParsedCollectionAliases(this.zkController.zkStateReader, false);

  String targetCollection = routedAlias.createCollectionsIfRequired(cmd);

  if (thisCollection.equals(targetCollection)) {
    // pass on through; we've reached the right collection
    super.processAdd(cmd);
  } else {
    // send to the right collection
    SolrCmdDistributor.Node targetLeaderNode = routeDocToSlice(targetCollection, cmd.getSolrInputDocument());
    cmdDistrib.distribAdd(cmd, Collections.singletonList(targetLeaderNode), new ModifiableSolrParams(outParamsToLeader));
  }
}
 
Example #7
Source File: SolrInformationServer.java    From SearchServices with GNU Lesser General Public License v3.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
private NamedList<Integer> getFacets(SolrQueryRequest request, String query, String field, int minCount)
{
    ModifiableSolrParams params =
            new ModifiableSolrParams(request.getParams())
                    .set(CommonParams.Q, query)
                    .set(CommonParams.ROWS, 0)
                    .set(FacetParams.FACET, true)
                    .set(FacetParams.FACET_FIELD, field)
                    .set(FacetParams.FACET_MINCOUNT, minCount);

    SolrQueryResponse response = cloud.getResponse(nativeRequestHandler, request, params);
    NamedList facetCounts = (NamedList) response.getValues().get("facet_counts");
    NamedList facetFields = (NamedList) facetCounts.get("facet_fields");
    return (NamedList) facetFields.get(field);
}
 
Example #8
Source File: TestDefaultStatsCache.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
protected void dfQuery(Object... q) throws Exception {
  final ModifiableSolrParams params = new ModifiableSolrParams();
  
  for (int i = 0; i < q.length; i += 2) {
    params.add(q[i].toString(), q[i + 1].toString());
  }
  
  final QueryResponse controlRsp = controlClient.query(params);
  
  // query a random server
  params.set("shards", shards);
  int which = r.nextInt(clients.size());
  SolrClient client = clients.get(which);
  QueryResponse rsp = client.query(params);
  checkResponse(controlRsp, rsp);
}
 
Example #9
Source File: SolrClientNodeStateProvider.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
static void fetchReplicaMetrics(String solrNode, ClientSnitchCtx ctx, Map<String, Object> metricsKeyVsTag) {
  if (!ctx.isNodeAlive(solrNode)) return;
  ModifiableSolrParams params = new ModifiableSolrParams();
  params.add("key", metricsKeyVsTag.keySet().toArray(new String[0]));
  try {
    SimpleSolrResponse rsp = ctx.invokeWithRetry(solrNode, CommonParams.METRICS_PATH, params);
    metricsKeyVsTag.forEach((key, tag) -> {
      Object v = Utils.getObjectByPath(rsp.nl, true, Arrays.asList("metrics", key));
      if (tag instanceof Function) {
        @SuppressWarnings({"unchecked"})
        Pair<String, Object> p = (Pair<String, Object>) ((Function) tag).apply(v);
        ctx.getTags().put(p.first(), p.second());
      } else {
        if (v != null) ctx.getTags().put(tag.toString(), v);
      }
    });
  } catch (Exception e) {
    log.warn("could not get tags from node {}", solrNode, e);
  }
}
 
Example #10
Source File: AbstractXJoinTestCase.java    From BioSolr with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
protected NamedList test(ModifiableSolrParams params, String componentName) {
  SolrCore core = h.getCore();

  SearchComponent sc = core.getSearchComponent(componentName);
  assertTrue("XJoinSearchComponent not found in solrconfig", sc != null);
    
  QParserPlugin qp = core.getQueryPlugin("xjoin");
  assertTrue("XJoinQParserPlugin not found in solrconfig", qp != null);
  
  params.add("q", "*:*");
  params.add("fq", "{!xjoin}" + componentName);

  SolrQueryResponse rsp = new SolrQueryResponse();
  rsp.add("responseHeader", new SimpleOrderedMap<>());
  SolrQueryRequest req = new LocalSolrQueryRequest(core, params);

  SolrRequestHandler handler = core.getRequestHandler("standard");
  handler.handleRequest(req, rsp);
  req.close();
  assertNull(rsp.getException());
    
  return rsp.getValues();
}
 
Example #11
Source File: FeaturesSelectionStream.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"unchecked"})
public NamedList<Double> call() throws Exception {
  ModifiableSolrParams params = new ModifiableSolrParams();
  HttpSolrClient solrClient = cache.getHttpSolrClient(baseUrl);

  params.add(DISTRIB, "false");
  params.add("fq","{!igain}");

  for(Map.Entry<String, String> entry : paramsMap.entrySet()) {
    params.add(entry.getKey(), entry.getValue());
  }

  params.add("outcome", outcome);
  params.add("positiveLabel", Integer.toString(positiveLabel));
  params.add("field", field);
  params.add("numTerms", String.valueOf(numTerms));

  QueryRequest request= new QueryRequest(params);
  QueryResponse response = request.process(solrClient);
  NamedList res = response.getResponse();
  return res;
}
 
Example #12
Source File: TestXJoinSearchComponent.java    From BioSolr with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("rawtypes")
public void testGroupedSimple() {
  ModifiableSolrParams params = new ModifiableSolrParams();    
  params.add("group", "true");
  params.add("group.field", "colour");
  params.add("group.format", "simple");
  NamedList results = test(params, "xjoin");
  testXJoinResults(results, "xjoin");
  NamedList grouped = (NamedList)results.get("grouped");
  NamedList colours = (NamedList)grouped.get("colour");
  assertEquals(2, colours.get("matches"));
  DocList docs = (DocList)colours.get("doclist");
  assertEquals(docs.size(), 2);
  DocIterator it = docs.iterator();
  assertTrue(it.hasNext());
  assertEquals(1, it.nextDoc());
  assertTrue(it.hasNext());
  assertEquals(3, it.nextDoc());
  assertFalse(it.hasNext());
}
 
Example #13
Source File: AlfrescoSolrUtils.java    From SearchServices with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Asserts that the input {@link ShardState} and the CoreAdmin.SUMMARY response give the same information.
 *
 * @param state the {@link ShardState} instance.
 * @param core the target {@link SolrCore} instance.
 */
public static void assertShardAndCoreSummaryConsistency(ShardState state, SolrCore core) {
    SolrParams params =
            new ModifiableSolrParams()
                    .add(CoreAdminParams.CORE, core.getName())
                    .add(CoreAdminParams.ACTION, "SUMMARY");

    SolrQueryRequest request = new LocalSolrQueryRequest(core, params);
    SolrQueryResponse response = new SolrQueryResponse();
    coreAdminHandler(core).handleRequest(request, response);

    NamedList<?> summary =
            ofNullable(response.getValues())
                    .map(values -> values.get("Summary"))
                    .map(NamedList.class::cast)
                    .map(values -> values.get(core.getName()))
                    .map(NamedList.class::cast)
                    .orElseGet(NamedList::new);

    assertEquals(state.getLastIndexedChangeSetId(), summary.get("Id for last Change Set in index"));
    assertEquals(state.getLastIndexedChangeSetCommitTime(), summary.get("Last Index Change Set Commit Time"));
    assertEquals(state.getLastIndexedTxCommitTime(), summary.get("Last Index TX Commit Time"));
    assertEquals(state.getLastIndexedTxId(), summary.get("Id for last TX in index"));
}
 
Example #14
Source File: QueryDocAuthorizationComponent.java    From incubator-sentry with Apache License 2.0 6 votes vote down vote up
@Override
public void prepare(ResponseBuilder rb) throws IOException {
  if (!enabled) {
    return;
  }

  String userName = sentryInstance.getUserName(rb.req);
  String superUser = System.getProperty("solr.authorization.superuser", "solr");
  if (superUser.equals(userName)) {
    return;
  }
  Set<String> roles = sentryInstance.getRoles(userName);
  if (roles != null && roles.size() > 0) {
    String filterQuery = getFilterQueryStr(roles);
    ModifiableSolrParams newParams = new ModifiableSolrParams(rb.req.getParams());
    newParams.add("fq", filterQuery);
    rb.req.setParams(newParams);
  } else {
    throw new SolrException(SolrException.ErrorCode.UNAUTHORIZED,
      "Request from user: " + userName +
      " rejected because user is not associated with any roles");
  }
}
 
Example #15
Source File: TestXJoinSearchComponent.java    From BioSolr with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("rawtypes")
public void testGroupedSimple() {
  ModifiableSolrParams params = new ModifiableSolrParams();    
  params.add("group", "true");
  params.add("group.field", "colour");
  params.add("group.format", "simple");
  NamedList results = test(params, "xjoin");
  testXJoinResults(results, "xjoin");
  NamedList grouped = (NamedList)results.get("grouped");
  NamedList colours = (NamedList)grouped.get("colour");
  assertEquals(2, colours.get("matches"));
  DocList docs = (DocList)colours.get("doclist");
  assertEquals(docs.size(), 2);
  DocIterator it = docs.iterator();
  assertTrue(it.hasNext());
  assertEquals(1, it.nextDoc());
  assertTrue(it.hasNext());
  assertEquals(3, it.nextDoc());
  assertFalse(it.hasNext());
}
 
Example #16
Source File: CarrotClusteringEngineTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Test
public void testPassingOfCustomFields() throws Exception {
  final ModifiableSolrParams params = new ModifiableSolrParams();
  params.add(CarrotParams.CUSTOM_FIELD_NAME, "intfield_i:intfield");
  params.add(CarrotParams.CUSTOM_FIELD_NAME, "floatfield_f:floatfield");
  params.add(CarrotParams.CUSTOM_FIELD_NAME, "heading:multi");
  
  // Let the echo mock clustering algorithm know which custom field to echo
  params.add("custom-fields", "intfield,floatfield,multi");
  
  final List<String> labels = getLabels(checkEngine(
      getClusteringEngine("echo"), 1, 1, new TermQuery(new Term("url",
          "custom_fields")), params).get(0));
  assertEquals(5, labels.size());
  assertEquals("Integer field", "10", labels.get(2));
  assertEquals("Float field", "10.5", labels.get(3));
  assertEquals("List field", "[first, second]", labels.get(4));
}
 
Example #17
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 #18
Source File: OverseerNodePrioritizer.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
private void invokeOverseerOp(String electionNode, String op) {
  ModifiableSolrParams params = new ModifiableSolrParams();
  ShardHandler shardHandler = ((HttpShardHandlerFactory)shardHandlerFactory).getShardHandler(httpClient);
  params.set(CoreAdminParams.ACTION, CoreAdminAction.OVERSEEROP.toString());
  params.set("op", op);
  params.set("qt", adminPath);
  params.set("electionNode", electionNode);
  ShardRequest sreq = new ShardRequest();
  sreq.purpose = 1;
  String replica = zkStateReader.getBaseUrlForNodeName(LeaderElector.getNodeName(electionNode));
  sreq.shards = new String[]{replica};
  sreq.actualShards = sreq.shards;
  sreq.params = params;
  shardHandler.submit(sreq, replica, sreq.params);
  shardHandler.takeCompletedOrError();
}
 
Example #19
Source File: StatsStream.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public StreamExpressionParameter toExpression(StreamFactory factory) throws IOException {
  // function name
  StreamExpression expression = new StreamExpression(factory.getFunctionName(this.getClass()));
  // collection
  if(collection.indexOf(',') > -1) {
    expression.addParameter("\""+collection+"\"");
  } else {
    expression.addParameter(collection);
  }

  // parameters
  ModifiableSolrParams tmpParams = new ModifiableSolrParams(params);

  for (Entry<String, String[]> param : tmpParams.getMap().entrySet()) {
    expression.addParameter(new StreamExpressionNamedParameter(param.getKey(),
        String.join(",", param.getValue())));
  }

  // metrics
  for(Metric metric : metrics){
    expression.addParameter(metric.toExpression(factory));
  }

  // zkHost
  expression.addParameter(new StreamExpressionNamedParameter("zkHost", zkHost));

  return expression;
}
 
Example #20
Source File: SolrTestCaseHS.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public static String getQueryResponse(String wt, SolrParams params) throws Exception {
  ModifiableSolrParams p = new ModifiableSolrParams(params);
  p.set("wt", wt);
  String path = p.get("qt");
  p.remove("qt");
  p.set("indent","true");

  DirectSolrConnection connection = new DirectSolrConnection(h.getCore());
  String raw = connection.request(path, p, null);
  return raw;
}
 
Example #21
Source File: SolrIndex.java    From titan1withtp3.1 with Apache License 2.0 5 votes vote down vote up
public SolrIndex(final Configuration config) throws BackendException {
    Preconditions.checkArgument(config!=null);
    configuration = config;

    mode = Mode.parse(config.get(SOLR_MODE));
    dynFields = config.get(DYNAMIC_FIELDS);
    keyFieldIds = parseKeyFieldsForCollections(config);
    maxResults = config.get(INDEX_MAX_RESULT_SET_SIZE);
    ttlField = config.get(TTL_FIELD);
    waitSearcher = config.get(WAIT_SEARCHER);

    if (mode==Mode.CLOUD) {
        String zookeeperUrl = config.get(SolrIndex.ZOOKEEPER_URL);
        CloudSolrClient cloudServer = new CloudSolrClient(zookeeperUrl, true);
        cloudServer.connect();
        solrClient = cloudServer;
    } else if (mode==Mode.HTTP) {
        HttpClient clientParams = HttpClientUtil.createClient(new ModifiableSolrParams() {{
            add(HttpClientUtil.PROP_ALLOW_COMPRESSION, config.get(HTTP_ALLOW_COMPRESSION).toString());
            add(HttpClientUtil.PROP_CONNECTION_TIMEOUT, config.get(HTTP_CONNECTION_TIMEOUT).toString());
            add(HttpClientUtil.PROP_MAX_CONNECTIONS_PER_HOST, config.get(HTTP_MAX_CONNECTIONS_PER_HOST).toString());
            add(HttpClientUtil.PROP_MAX_CONNECTIONS, config.get(HTTP_GLOBAL_MAX_CONNECTIONS).toString());
        }});

        solrClient = new LBHttpSolrClient(clientParams, config.get(HTTP_URLS));


    } else {
        throw new IllegalArgumentException("Unsupported Solr operation mode: " + mode);
    }
}
 
Example #22
Source File: KnnStream.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public void open() throws IOException {
  cloudSolrClient = cache.getCloudSolrClient(zkHost);
  ModifiableSolrParams params = getParams(this.props);

  StringBuilder builder = new StringBuilder();

  for(String key : mltParams) {
    if(params.get(key) != null) {
      builder.append(' ').append(key).append('=').append(params.get(key));
      params.remove(key);
    }
  }

  String k = params.get("k");

  if(k != null) {
    params.add(ROWS, k);
    params.remove(k);
  }

  params.add(Q, "{!mlt"+builder.toString()+"}"+id);

  QueryRequest request = new QueryRequest(params);
  try {
    QueryResponse response = request.process(cloudSolrClient, collection);
    SolrDocumentList docs = response.getResults();
    documentIterator = docs.iterator();
  } catch (Exception e) {
    throw new IOException(e);
  }
}
 
Example #23
Source File: CollectionAdminRequest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public SolrParams getParams() {
  ModifiableSolrParams params = (ModifiableSolrParams) super.getParams();
  params.set(CoreAdminParams.NAME, aliasName);
  params.set("collections", aliasedCollections);
  return params;
}
 
Example #24
Source File: CloudHttp2SolrClientTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private void queryReplicaType(CloudHttp2SolrClient cloudClient,
                              Replica.Type typeToQuery,
                              String collectionName)
    throws Exception
{
  SolrQuery qRequest = new SolrQuery("*:*");

  ModifiableSolrParams qParams = new ModifiableSolrParams();
  qParams.add(ShardParams.SHARDS_PREFERENCE, ShardParams.SHARDS_PREFERENCE_REPLICA_TYPE + ":" + typeToQuery.toString());
  qParams.add(ShardParams.SHARDS_INFO, "true");
  qRequest.add(qParams);

  Map<String, String> replicaTypeToReplicas = mapReplicasToReplicaType(getCollectionState(collectionName));

  QueryResponse qResponse = cloudClient.query(collectionName, qRequest);

  Object shardsInfo = qResponse.getResponse().get(ShardParams.SHARDS_INFO);
  assertNotNull("Unable to obtain "+ShardParams.SHARDS_INFO, shardsInfo);

  // Iterate over shards-info and check what cores responded
  SimpleOrderedMap<?> shardsInfoMap = (SimpleOrderedMap<?>)shardsInfo;
  @SuppressWarnings({"unchecked"})
  Iterator<Map.Entry<String, ?>> itr = shardsInfoMap.asMap(100).entrySet().iterator();
  List<String> shardAddresses = new ArrayList<String>();
  while (itr.hasNext()) {
    Map.Entry<String, ?> e = itr.next();
    assertTrue("Did not find map-type value in "+ShardParams.SHARDS_INFO, e.getValue() instanceof Map);
    String shardAddress = (String)((Map)e.getValue()).get("shardAddress");
    if (shardAddress.endsWith("/")) {
      shardAddress = shardAddress.substring(0, shardAddress.length() - 1);
    }
    assertNotNull(ShardParams.SHARDS_INFO+" did not return 'shardAddress' parameter", shardAddress);
    shardAddresses.add(shardAddress);
  }
  assertEquals("Shard addresses must be of size 1, since there is only 1 shard in the collection", 1, shardAddresses.size());

  assertEquals("Make sure that the replica queried was the replicaType desired", typeToQuery.toString().toUpperCase(Locale.ROOT), replicaTypeToReplicas.get(shardAddresses.get(0)).toUpperCase(Locale.ROOT));
}
 
Example #25
Source File: TestRangeQuery.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private long doRangeQuery(boolean mv, String start, String end, String field, String[] qRange) throws Exception {
  ModifiableSolrParams params = new ModifiableSolrParams();
  params.set("q", "field_" + (mv?"mv_":"sv_") + field + ":" + start + qRange[0] + " TO " + qRange[1] + end);
  SolrQueryRequest req = req(params);
  try {
    return (long) h.queryAndResponse("", req).getToLog().get("hits");
  } finally {
    req.close();
  }

}
 
Example #26
Source File: TestDistribPackageStore.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public static void postFile(SolrClient client, ByteBuffer buffer, String name, String sig)
    throws SolrServerException, IOException {
  String resource = "/cluster/files" + name;
  ModifiableSolrParams params = new ModifiableSolrParams();
  params.add("sig", sig);
  V2Response rsp = new V2Request.Builder(resource)
      .withMethod(SolrRequest.METHOD.PUT)
      .withPayload(buffer)
      .forceV2(true)
      .withMimeType("application/octet-stream")
      .withParams(params)
      .build()
      .process(client);
  assertEquals(name, rsp.getResponse().get(CommonParams.FILE));
}
 
Example #27
Source File: MCRSolrProxyServlet.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
private static ModifiableSolrParams toSolrParams(Map<String, String[]> parameters) {
    // to maintain order
    LinkedHashMap<String, String[]> copy = new LinkedHashMap<>(parameters);
    ModifiableSolrParams solrParams = new ModifiableSolrParams(copy);
    if (!parameters.containsKey("version") && !parameters.containsKey("wt")) {
        solrParams.set("version", SOLR_QUERY_XML_PROTOCOL_VERSION);
    }
    return solrParams;
}
 
Example #28
Source File: TestSolrCloudWithDelegationTokens.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Test HttpSolrServer's delegation token support
 */
@Test
public void testDelegationTokenSolrClient() throws Exception {
  // Get token
  String token = getDelegationToken(null, "bar", solrClientPrimary);
  assertNotNull(token);

  @SuppressWarnings({"rawtypes"})
  SolrRequest request = getAdminRequest(new ModifiableSolrParams());

  // test without token
  final HttpSolrClient ssWoToken =
    new HttpSolrClient.Builder(solrClientPrimary.getBaseURL().toString())
        .withResponseParser(solrClientPrimary.getParser())
        .build();
  try {
    doSolrRequest(ssWoToken, request, ErrorCode.UNAUTHORIZED.code);
  } finally {
    ssWoToken.close();
  }

  final HttpSolrClient ssWToken = new HttpSolrClient.Builder(solrClientPrimary.getBaseURL().toString())
      .withKerberosDelegationToken(token)
      .withResponseParser(solrClientPrimary.getParser())
      .build();
  try {
    // test with token via property
    doSolrRequest(ssWToken, request, HttpStatus.SC_OK);

    // test with param -- should throw an exception
    ModifiableSolrParams tokenParam = new ModifiableSolrParams();
    tokenParam.set("delegation", "invalidToken");
    expectThrows(IllegalArgumentException.class,
        () -> doSolrRequest(ssWToken, getAdminRequest(tokenParam), ErrorCode.FORBIDDEN.code));
  } finally {
    ssWToken.close();
  }
}
 
Example #29
Source File: TestSimple.java    From BioSolr with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("rawtypes")
public void testSimpleXJoinResultsFactory() {
  ModifiableSolrParams params = new ModifiableSolrParams();
  params.add("fl", "*, score");
  params.add("xjoin", "false");
  params.add("xjoin5", "true");
  params.add("xjoin5.fl", "*");
  
  // score boosts using value source parser
  params.add("defType", "edismax");
  params.add("bf", "xjoin5(value)");
  
  NamedList results = test(params, "xjoin5");
  ResultContext response = (ResultContext)results.get("response");
  DocList docs = response.docs;
  assertEquals(2, docs.size());
  DocIterator it = docs.iterator();
  assertTrue(it.hasNext());
  assertEquals(0, it.nextDoc());
  double score0 = it.score();
  assertTrue(it.hasNext());
  assertEquals(2, it.nextDoc());
  double score2 = it.score();
  assertFalse(it.hasNext());
 
  // bf score boost for testid=0 only
  assertTrue(score0 > score2);
  
  List externalList = (List)((NamedList)results.get("xjoin5")).get("external");
  NamedList hit0 = (NamedList)externalList.get(0);
  assertEquals("0", hit0.get("joinId"));
  NamedList doc0 = (NamedList)hit0.get("doc");
  assertEquals("red", doc0.get("colour"));
  assertEquals(10.5, doc0.get("value"));
}
 
Example #30
Source File: AutoscalingHistoryHandlerTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private SolrDocumentList queryAndAssertDocs(ModifiableSolrParams query, SolrClient client, int expected) throws Exception {
  QueryResponse rsp = client.query(query);
  SolrDocumentList docs = rsp.getResults();
  if (docs.size() != expected) {
    log.info("History query: {}", query);
    log.info("Wrong response: {}", rsp);
    ModifiableSolrParams fullQuery = params(CommonParams.QT, CommonParams.AUTOSCALING_HISTORY_PATH);
    if (log.isInfoEnabled()) {
      log.info("Full response: {}", client.query(fullQuery));
    }
  }
  assertEquals("Wrong number of documents", expected, docs.size());
  return docs;
}