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

The following examples show how to use org.apache.solr.common.params.MapSolrParams. 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: AdminHandlersProxyTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Test
public void proxySystemInfoHandlerOneNode() {
  Set<String> nodes = solrClient.getClusterStateProvider().getLiveNodes();
  assertEquals(2, nodes.size());
  nodes.forEach(node -> {
    MapSolrParams params = new MapSolrParams(Collections.singletonMap("nodes", node));
    GenericSolrRequest req = new GenericSolrRequest(SolrRequest.METHOD.GET, "/admin/info/system", params);
    SimpleSolrResponse rsp = null;
    try {
      rsp = req.process(solrClient, null);
    } catch (Exception e) {
      fail("Exception while proxying request to node " + node);
    }
    NamedList<Object> nl = rsp.getResponse();
    assertEquals(2, nl.size());
    assertEquals("solrcloud", ((NamedList)nl.get(nl.getName(1))).get("mode"));
    assertEquals(nl.getName(1), ((NamedList)nl.get(nl.getName(1))).get("node"));
  });
}
 
Example #2
Source File: SolrCellMorphlineTest.java    From kite with Apache License 2.0 6 votes vote down vote up
/**
 * Test that the ContentHandler properly strips the illegal characters
 */
@Test
public void testTransformValue() {
  String fieldName = "user_name";
  assertFalse("foobar".equals(getFoobarWithNonChars()));

  Metadata metadata = new Metadata();
  // load illegal char string into a metadata field and generate a new document,
  // which will cause the ContentHandler to be invoked.
  metadata.set(fieldName, getFoobarWithNonChars());
  StripNonCharSolrContentHandlerFactory contentHandlerFactory =
    new StripNonCharSolrContentHandlerFactory(ExtractionDateUtil.DEFAULT_DATE_FORMATS);
  IndexSchema schema = h.getCore().getLatestSchema();
  SolrContentHandler contentHandler =
    contentHandlerFactory.createSolrContentHandler(metadata, new MapSolrParams(new HashMap()), schema);
  SolrInputDocument doc = contentHandler.newDocument();
  String foobar = doc.getFieldValue(fieldName).toString();
  assertTrue("foobar".equals(foobar));
}
 
Example #3
Source File: TermRecognitionRequestHandler.java    From jate with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * This request handler supports configuration options defined at the top
 * level as well as those in typical Solr 'defaults', 'appends', and
 * 'invariants'. The top level ones are treated as invariants.
 */
private void setTopInitArgsAsInvariants(SolrQueryRequest req) {
    // First convert top level initArgs to SolrParams
    HashMap<String, String> map = new HashMap<String, String>(initArgs.size());
    for (int i = 0; i < initArgs.size(); i++) {
        Object val = initArgs.getVal(i);
        if (val != null && !(val instanceof NamedList))
            map.put(initArgs.getName(i), val.toString());
    }
    if (map.isEmpty())
        return;// short circuit; nothing to do
    SolrParams topInvariants = new MapSolrParams(map);
    // By putting the top level into the 1st arg, it overrides
    // request params in 2nd arg.
    req.setParams(SolrParams.wrapDefaults(topInvariants, req.getParams()));
}
 
Example #4
Source File: TestRegexExtract.java    From solr-researcher with Apache License 2.0 6 votes vote down vote up
@Test
public void testRelaxMM() {
  Map<String, String> m = new HashMap<String, String>();
  m.put("q", "query:\"{!type=edismax qf='title description body' v='large rectangle' relax='on'}\" +yearpub:2008");
  SolrParams params = new MapSolrParams(m);
  String relaxedQuery = extract.relaxMM(params, "-1");
  assertEquals("query:\"{!type=edismax qf='title description body' v='large rectangle' relax='on' mm='-1'}\" +yearpub:2008", relaxedQuery);
  
  m.put("q", "query:\"{!type=edismax qf='title description body' v='large rectangle' relax='on' mm='100%'}\" +yearpub:2008");
  relaxedQuery = extract.relaxMM(params, "-1");
  assertEquals("query:\"{!type=edismax qf='title description body' v='large rectangle' relax='on' mm='-1'}\" +yearpub:2008", relaxedQuery);
  
  m.put("q", "query:\"{!type=edismax qf='title description body' v='large rectangle' mm='100%'}\" +yearpub:2008");
  relaxedQuery = extract.relaxMM(params, "-1");
  assertEquals("query:\"{!type=edismax qf='title description body' v='large rectangle' mm='100%'}\" +yearpub:2008", relaxedQuery);
}
 
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: SSLMigrationTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
private void setUrlScheme(String value) throws Exception {
  @SuppressWarnings("rawtypes")
  Map m = makeMap("action", CollectionAction.CLUSTERPROP.toString()
      .toLowerCase(Locale.ROOT), "name", "urlScheme", "val", value);
  @SuppressWarnings("unchecked")
  SolrParams params = new MapSolrParams(m);
  @SuppressWarnings({"rawtypes"})
  SolrRequest request = new QueryRequest(params);
  request.setPath("/admin/collections");
  
  List<String> urls = new ArrayList<String>();
  for(Replica replica : getReplicas()) {
    urls.add(replica.getStr(ZkStateReader.BASE_URL_PROP));
  }
  //Create new SolrServer to configure new HttpClient w/ SSL config
  try (SolrClient client = getLBHttpSolrClient(urls.toArray(new String[]{}))) {
    client.request(request);
  }
}
 
Example #7
Source File: AutocompleteUpdateRequestProcessor.java    From solr-autocomplete with Apache License 2.0 6 votes vote down vote up
private SolrInputDocument fetchExistingOrCreateNewSolrDoc(String id) throws SolrServerException, IOException {
  Map<String, String> p = new HashMap<String, String>();
  p.put("q", PHRASE + ":\"" + ClientUtils.escapeQueryChars(id) + "\"");
  
  SolrParams params = new MapSolrParams(p);
  
  QueryResponse res = solrAC.query(params);
  
  if (res.getResults().size() == 0) {
    return new SolrInputDocument();
  } else if (res.getResults().size() == 1) {
    SolrDocument doc = res.getResults().get(0);
    SolrInputDocument tmp = new SolrInputDocument();
    
    for (String fieldName : doc.getFieldNames()) {
      tmp.addField(fieldName, doc.getFieldValue(fieldName));
    }
    return tmp;
  } else {
    throw new IllegalStateException("Query with params : " + p + " returned more than 1 hit!");
  }
}
 
Example #8
Source File: TestPackages.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
private void verifyCmponent(SolrClient client, String COLLECTION_NAME,
String componentType, String componentName, String pkg, String version) throws Exception {
  @SuppressWarnings({"unchecked"})
  SolrParams params = new MapSolrParams((Map) Utils.makeMap("collection", COLLECTION_NAME,
      WT, JAVABIN,
      "componentName", componentName,
      "meta", "true"));

  GenericSolrRequest req1 = new GenericSolrRequest(SolrRequest.METHOD.GET,
      "/config/" + componentType, params);
  TestDistribPackageStore.assertResponseValues(10,
      client,
      req1, Utils.makeMap(
          ":config:" + componentType + ":" + componentName + ":_packageinfo_:package", pkg,
          ":config:" + componentType + ":" + componentName + ":_packageinfo_:version", version
      ));
}
 
Example #9
Source File: BaseTestRuleBasedAuthorizationPlugin.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Test
public void testAllPermissionDeniesActionsWhenUserIsNotCorrectRole() {
  SolrRequestHandler handler = new UpdateRequestHandler();
  assertThat(handler, new IsInstanceOf(PermissionNameProvider.class));
  setUserRole("dev", "dev");
  setUserRole("admin", "admin");
  addPermission("all", "admin");
  checkRules(makeMap("resource", "/update",
      "userPrincipal", "dev",
      "requestType", RequestType.UNKNOWN,
      "collectionRequests", "go",
      "handler", new UpdateRequestHandler(),
      "params", new MapSolrParams(singletonMap("key", "VAL2")))
      , FORBIDDEN);

  handler = new PropertiesRequestHandler();
  assertThat(handler, new IsNot<>(new IsInstanceOf(PermissionNameProvider.class)));
  checkRules(makeMap("resource", "/admin/info/properties",
      "userPrincipal", "dev",
      "requestType", RequestType.UNKNOWN,
      "collectionRequests", "go",
      "handler", handler,
      "params", new MapSolrParams(emptyMap()))
      , FORBIDDEN);
}
 
Example #10
Source File: BaseTestRuleBasedAuthorizationPlugin.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Test
public void testAllPermissionAllowsActionsWhenAssociatedRoleIsWildcard() {
  SolrRequestHandler handler = new UpdateRequestHandler();
  assertThat(handler, new IsInstanceOf(PermissionNameProvider.class));
  setUserRole("dev", "dev");
  setUserRole("admin", "admin");
  addPermission("all", "*");
  checkRules(makeMap("resource", "/update",
      "userPrincipal", "dev",
      "requestType", RequestType.UNKNOWN,
      "collectionRequests", "go",
      "handler", new UpdateRequestHandler(),
      "params", new MapSolrParams(singletonMap("key", "VAL2")))
      , STATUS_OK);

  handler = new PropertiesRequestHandler();
  assertThat(handler, new IsNot<>(new IsInstanceOf(PermissionNameProvider.class)));
  checkRules(makeMap("resource", "/admin/info/properties",
      "userPrincipal", "dev",
      "requestType", RequestType.UNKNOWN,
      "collectionRequests", "go",
      "handler", handler,
      "params", new MapSolrParams(emptyMap()))
      , STATUS_OK);
}
 
Example #11
Source File: BaseTestRuleBasedAuthorizationPlugin.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Test
public void testAllPermissionAllowsActionsWhenUserHasCorrectRole() {
  SolrRequestHandler handler = new UpdateRequestHandler();
  assertThat(handler, new IsInstanceOf(PermissionNameProvider.class));
  setUserRole("dev", "dev");
  setUserRole("admin", "admin");
  addPermission("all", "dev", "admin");
  checkRules(makeMap("resource", "/update",
      "userPrincipal", "dev",
      "requestType", RequestType.UNKNOWN,
      "collectionRequests", "go",
      "handler", handler,
      "params", new MapSolrParams(singletonMap("key", "VAL2")))
      , STATUS_OK);

  handler = new PropertiesRequestHandler();
  assertThat(handler, new IsNot<>(new IsInstanceOf(PermissionNameProvider.class)));
  checkRules(makeMap("resource", "/admin/info/properties",
      "userPrincipal", "dev",
      "requestType", RequestType.UNKNOWN,
      "collectionRequests", "go",
      "handler", handler,
      "params", new MapSolrParams(emptyMap()))
      , STATUS_OK);
}
 
Example #12
Source File: AbstractSubTypeFieldType.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
protected void init(IndexSchema schema, Map<String, String> args) {
  super.init(schema, args);
  this.schema = schema;
  //it's not a first class citizen for the IndexSchema
  SolrParams p = new MapSolrParams(args);
  subFieldType = p.get(SUB_FIELD_TYPE);
  subSuffix = p.get(SUB_FIELD_SUFFIX);
  if (subFieldType != null) {
    args.remove(SUB_FIELD_TYPE);
    subType = schema.getFieldTypeByName(subFieldType.trim());
    suffix = POLY_FIELD_SEPARATOR + subType.typeName;
  } else if (subSuffix != null) {
    args.remove(SUB_FIELD_SUFFIX);
    suffix = subSuffix;
  } else {
    throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "The field type: " + typeName
            + " must specify the " +
            SUB_FIELD_TYPE + " attribute or the " + SUB_FIELD_SUFFIX + " attribute.");
  }
}
 
Example #13
Source File: BlobHandler.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
private void verifyWithRealtimeGet(String blobName, long version, SolrQueryRequest req, Map<String, Object> doc) {
  for (; ; ) {
    SolrQueryResponse response = new SolrQueryResponse();
    String id = blobName + "/" + version;
    forward(req, "/get", new MapSolrParams(singletonMap(ID, id)), response);
    if (response.getValues().get("doc") == null) {
      //ensure that the version does not exist
      return;
    } else {
      log.info("id {} already exists trying next ", id);
      version++;
      doc.put("version", version);
      id = blobName + "/" + version;
      doc.put(ID, id);
    }
  }

}
 
Example #14
Source File: AggregationWaitable.java    From semantic-knowledge-graph with Apache License 2.0 5 votes vote down vote up
public SolrParams buildFacetParams()
{
    LinkedHashMap<String, String> paramMap = new LinkedHashMap<>();
    paramMap.put("facet.version", "1");
    paramMap.put("wt", "json");
    paramMap.put(FacetParams.FACET, "true");
    return new MapSolrParams(paramMap);
}
 
Example #15
Source File: StatsComponentTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public void testFieldStatisticsResultsNumericFieldAlwaysMissing() throws Exception {
  SolrCore core = h.getCore();
  assertU(adoc("id", "1"));
  assertU(adoc("id", "2"));
  assertU(commit());
  assertU(adoc("id", "3"));
  assertU(adoc("id", "4"));
  assertU(commit());

  Map<String, String> args = new HashMap<>();
  args.put(CommonParams.Q, "*:*");
  args.put(StatsParams.STATS, "true");
  args.put(StatsParams.STATS_FIELD, "active_i");
  args.put("indent", "true");
  SolrQueryRequest req = new LocalSolrQueryRequest(core, new MapSolrParams(args));

  assertQ("test string statistics values", req
          ,"//lst[@name='active_i']/long[@name='count'][.='0']"
          ,"//lst[@name='active_i']/long[@name='missing'][.='4']"

          ,"//lst[@name='active_i']/null[@name='min']"
          ,"//lst[@name='active_i']/null[@name='max']"
          ,"//lst[@name='active_i']/double[@name='sum'][.='0.0']"
          ,"//lst[@name='active_i']/double[@name='sumOfSquares'][.='0.0']"
          ,"//lst[@name='active_i']/double[@name='stddev'][.='0.0']"
          ,"//lst[@name='active_i']/double[@name='mean'][.='NaN']"
          // if new stats are supported, this will break - update test to assert values for each
          ,"count(//lst[@name='active_i']/*)=8"
          
          );

  // NOTE: empty set percentiles covered in testPercentiles()

  assertQ("test cardinality of missing"
          , req("q", "*:*", "stats", "true", "stats.field", "{!cardinality=true}active_i")
          ,"//lst[@name='active_i']/long[@name='cardinality'][.='0']"
          );

}
 
Example #16
Source File: StatsComponentTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public void testFieldStatisticsResultsStringFieldAlwaysMissing() throws Exception {
  SolrCore core = h.getCore();
  assertU(adoc("id", "1"));
  assertU(adoc("id", "2"));
  assertU(commit());
  assertU(adoc("id", "3"));
  assertU(adoc("id", "4"));
  assertU(commit());

  Map<String, String> args = new HashMap<>();
  args.put(CommonParams.Q, "*:*");
  args.put(StatsParams.STATS, "true");
  args.put(StatsParams.STATS_FIELD, "active_s");
  args.put("indent", "true");
  SolrQueryRequest req = new LocalSolrQueryRequest(core, new MapSolrParams(args));

  assertQ("test string statistics values", req
          ,"//lst[@name='active_s']/long[@name='count'][.='0']"
          ,"//lst[@name='active_s']/long[@name='missing'][.='4']"

          ,"//lst[@name='active_s']/null[@name='min']"
          ,"//lst[@name='active_s']/null[@name='max']"
          // if new stats are supported, this will break - update test to assert values for each
          ,"count(//lst[@name='active_s']/*)=4"
          );

  assertQ("test string statistics values"
          , req("q", "*:*", "stats", "true", "stats.field", "{!cardinality=true}active_s")
          ,"//lst[@name='active_s']/long[@name='cardinality'][.='0']"
          );

}
 
Example #17
Source File: StatsComponentTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public void testFieldStatisticsDocValuesAndMultiValuedIntegerFacetStats() throws Exception {
  SolrCore core = h.getCore();
  String fieldName = "cat_intDocValues";
  // precondition for the test
  SchemaField catDocValues = core.getLatestSchema().getField(fieldName);
  assertTrue("schema no longer satisfies test requirements: cat_docValues no longer multivalued", catDocValues.multiValued());
  assertTrue("schema no longer satisfies test requirements: cat_docValues fieldtype no longer single valued", !catDocValues.getType().isMultiValued());
  assertTrue("schema no longer satisfies test requirements: cat_docValues no longer has docValues", catDocValues.hasDocValues());

  List<FldType> types = new ArrayList<>();
  types.add(new FldType("id", ONE_ONE, new SVal('A', 'Z', 4, 4)));
  types.add(new FldType(fieldName, ONE_ONE, new IRange(0, 0)));

  Doc d1 = createDocValuesDocument(types, fieldName, "1", -1, 3, 5);
  updateJ(toJSON(d1), null);

  Doc d2 = createDocValuesDocument(types, fieldName, "2", 3, -2, 6);
  updateJ(toJSON(d2), null);

  Doc d3 = createDocValuesDocument(types, fieldName, "3", 16, -3, 11);
  updateJ(toJSON(d3), null);

  assertU(commit());

  Map<String, String> args = new HashMap<>();
  args.put(CommonParams.Q, "*:*");
  args.put(StatsParams.STATS, "true");
  args.put(StatsParams.STATS_FIELD, fieldName);
  args.put(StatsParams.STATS_FACET, fieldName);
  args.put(StatsParams.STATS_CALC_DISTINCT, "true");
  args.put("indent", "true");

  SolrQueryRequest req = new LocalSolrQueryRequest(core, new MapSolrParams(args));

  assertQEx("can not use FieldCache on multivalued field: cat_intDocValues", req, 400);

}
 
Example #18
Source File: XsltUpdateRequestHandlerTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdate() throws Exception
{
  String xml = 
    "<random>" +
    " <document>" +
    "  <node name=\"id\" value=\"12345\"/>" +
    "  <node name=\"name\" value=\"kitten\"/>" +
    "  <node name=\"text\" enhance=\"3\" value=\"some other day\"/>" +
    "  <node name=\"title\" enhance=\"4\" value=\"A story\"/>" +
    "  <node name=\"timestamp\" enhance=\"5\" value=\"2011-07-01T10:31:57.140Z\"/>" +
    " </document>" +
    "</random>";

  Map<String,String> args = new HashMap<>();
  args.put(CommonParams.TR, "xsl-update-handler-test.xsl");
    
  SolrCore core = h.getCore();
  LocalSolrQueryRequest req = new LocalSolrQueryRequest( core, new MapSolrParams( args) );
  ArrayList<ContentStream> streams = new ArrayList<>();
  streams.add(new ContentStreamBase.StringStream(xml));
  req.setContentStreams(streams);
  SolrQueryResponse rsp = new SolrQueryResponse();
  try (UpdateRequestHandler handler = new UpdateRequestHandler()) {
    handler.init(new NamedList<String>());
    handler.handleRequestBody(req, rsp);
  }
  StringWriter sw = new StringWriter(32000);
  QueryResponseWriter responseWriter = core.getQueryResponseWriter(req);
  responseWriter.write(sw,req,rsp);
  req.close();
  String response = sw.toString();
  assertU(response);
  assertU(commit());

  assertQ("test document was correctly committed", req("q","*:*")
          , "//result[@numFound='1']"
          , "//str[@name='id'][.='12345']"
      );
}
 
Example #19
Source File: ExportHandler.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {
  try {
    super.handleRequestBody(req, rsp);
  } catch (Exception e) {
    rsp.setException(e);
  }
  String wt = req.getParams().get(CommonParams.WT, JSON);
  if("xsort".equals(wt)) wt = JSON;
  Map<String, String> map = new HashMap<>(1);
  map.put(CommonParams.WT, ReplicationHandler.FILE_STREAM);
  req.setParams(SolrParams.wrapDefaults(new MapSolrParams(map),req.getParams()));
  rsp.add(ReplicationHandler.FILE_STREAM, new ExportWriter(req, rsp, wt, initialStreamContext));
}
 
Example #20
Source File: AutoAddReplicasIntegrationTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private void disableAutoAddReplicasInCluster() throws SolrServerException, IOException {
  @SuppressWarnings({"rawtypes"})
  Map m = makeMap(
      "action", CollectionParams.CollectionAction.CLUSTERPROP.toLower(),
      "name", ZkStateReader.AUTO_ADD_REPLICAS,
      "val", "false");
  @SuppressWarnings({"unchecked"})
  QueryRequest request = new QueryRequest(new MapSolrParams(m));
  request.setPath("/admin/collections");
  cluster.getSolrClient().request(request);
}
 
Example #21
Source File: AutoAddReplicasIntegrationTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private void enableAutoAddReplicasInCluster() throws SolrServerException, IOException {
  @SuppressWarnings({"rawtypes"})
  Map m = makeMap(
      "action", CollectionParams.CollectionAction.CLUSTERPROP.toLower(),
      "name", ZkStateReader.AUTO_ADD_REPLICAS);
  @SuppressWarnings({"unchecked"})
  QueryRequest request = new QueryRequest(new MapSolrParams(m));
  request.setPath("/admin/collections");
  cluster.getSolrClient().request(request);
}
 
Example #22
Source File: AutoScalingHandlerTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public void testSuggestionsWithPayload() throws Exception {
  CloudSolrClient solrClient = cluster.getSolrClient();
  String COLLNAME = "testSuggestionsWithPayload.COLL";
  CollectionAdminResponse adminResponse = CollectionAdminRequest.createCollection(COLLNAME, CONFIGSET_NAME, 1, 2)
      .setMaxShardsPerNode(4)
      .process(solrClient);
  cluster.waitForActiveCollection(COLLNAME, 1, 2);
  DocCollection collection = solrClient.getClusterStateProvider().getCollection(COLLNAME);
  Replica aReplica = collection.getReplicas().get(0);

  String configPayload = "{\n" +
      "  'cluster-policy': [{'replica': 0, 'node': '_NODE'}]\n" +
      "}";
  configPayload = configPayload.replaceAll("_NODE", aReplica.getNodeName());
  @SuppressWarnings({"rawtypes"})
  SolrRequest req = AutoScalingRequest.create(SolrRequest.METHOD.POST, "/suggestions", configPayload);
  NamedList<Object> response = solrClient.request(req);
  assertFalse(((Collection) response.get("suggestions")).isEmpty());
  String replicaName = response._getStr("suggestions[0]/operation/command/move-replica/replica", null);
  boolean[] passed = new boolean[]{false};
  collection.forEachReplica((s, replica) -> {
    if (replica.getName().equals(replicaName) && replica.getNodeName().equals(aReplica.getNodeName())) {
      passed[0] = true;
    }
  });
  assertTrue(passed[0]);

  req = AutoScalingRequest.create(SolrRequest.METHOD.POST, "/suggestions", configPayload, new MapSolrParams(Collections.singletonMap("type", repair.name())));
  response = solrClient.request(req);
  assertTrue(((Collection) response.get("suggestions")).isEmpty());

  CollectionAdminRequest.deleteCollection(COLLNAME)
      .process(cluster.getSolrClient());
}
 
Example #23
Source File: TestRegexExtract.java    From solr-researcher with Apache License 2.0 5 votes vote down vote up
@Test
public void testRelax() {
  Map<String, String> m = new HashMap<String, String>();
  m.put("q", "query:\"{!type=edismax qf='title description body' v='large rectangle'}  \" +yearpub:2008");
  SolrParams params = new MapSolrParams(m);
  String userQuery = "large rectangle";
  String relaxedUserQuery = "rectangle";
  String relaxedQuery = extract.relaxQuery(params, userQuery, relaxedUserQuery);
  assertEquals("query:\"{!type=edismax qf='title description body' v='rectangle'}  \" +yearpub:2008", relaxedQuery);
}
 
Example #24
Source File: DataImportHandler.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override

  public void init(@SuppressWarnings({"rawtypes"})NamedList args) {
    super.init(args);
    Map<String,String> macro = new HashMap<>();
    macro.put("expandMacros", "false");
    defaults = SolrParams.wrapDefaults(defaults, new MapSolrParams(macro));
  }
 
Example #25
Source File: StatsComponentTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public void testFieldStatisticsResultsDateFieldAlwaysMissing() throws Exception {
  SolrCore core = h.getCore();

  assertU(adoc("id", "1"));
  assertU(adoc("id", "2"));
  assertU(commit());
  assertU(adoc("id", "3"));
  assertU(commit());

  Map<String, String> args = new HashMap<>();
  args.put(CommonParams.Q, "*:*");
  args.put(StatsParams.STATS, "true");
  args.put(StatsParams.STATS_FIELD, "active_dt");
  args.put("indent", "true");
  SolrQueryRequest req = new LocalSolrQueryRequest(core, new MapSolrParams(args));

  assertQ("test string statistics values", req
          ,"//lst[@name='active_dt']/long[@name='count'][.='0']"
          ,"//lst[@name='active_dt']/long[@name='missing'][.='3']"

          ,"//lst[@name='active_dt']/null[@name='min']"
          ,"//lst[@name='active_dt']/null[@name='max']"
          ,"//lst[@name='active_dt']/null[@name='mean']"
          ,"//lst[@name='active_dt']/double[@name='sum'][.='0.0']"
          ,"//lst[@name='active_dt']/double[@name='sumOfSquares'][.='0.0']"
          ,"//lst[@name='active_dt']/double[@name='stddev'][.='0.0']"

          // if new stats are supported, this will break - update test to assert values for each
          ,"count(//lst[@name='active_dt']/*)=8"
          );
  
  assertQ("cardinality"
          , req("q","*:*", "stats", "true", "stats.field", "{!cardinality=true}active_dt")
          ,"//lst[@name='active_dt']/long[@name='cardinality'][.='0']"
          );

}
 
Example #26
Source File: FacetFieldAdapterTest.java    From semantic-knowledge-graph with Apache License 2.0 5 votes vote down vote up
@Before
public void init() {
    HashMap<String, String> paramMap = new HashMap<>();
    paramMap.put("title.facet-field", "id-title");
    paramMap.put("title.key", "id");
    paramMap.put("title.top.facet-field", "id-title");
    paramMap.put("tags.facet-field", "id-title");
    paramMap.put("tags.key", "id");
    paramMap.put("tags.top.facet-field", "id-title");
    paramMap.put("tags.top.key", "id");
    paramMap.put("rank.facet-field", "level-description");
    paramMap.put("rank.key", "level");
    paramMap.put("field.with.dots.facet-field", "id-value");
    paramMap.put("field.with.dots.key", "id");

    new MockUp<FieldChecker>()
    {
        @Mock void checkField(SolrQueryRequest req, String field, String facetField)
        {
            if(!fieldList.contains(field))
                throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "you tell me do things i come runnin");
        }
    };

    fieldList = Arrays.asList(fieldNames);
    invariants = new MapSolrParams(paramMap);
}
 
Example #27
Source File: AggregationWaitableTest.java    From semantic-knowledge-graph with Apache License 2.0 5 votes vote down vote up
@Test
public void buildFacetParams(){
    AggregationWaitable target = new AggregationWaitable(context, adapter, "query", "testField",0, 0);

    MapSolrParams actual = Deencapsulation.invoke(target, "buildFacetParams");

    Assert.assertEquals("json".compareTo(actual.get("wt")), 0);
    Assert.assertEquals("1".compareTo(actual.get("facet.version")), 0);
    Assert.assertEquals("true".compareTo(actual.get(FacetParams.FACET)), 0);
}
 
Example #28
Source File: UsingSolrJRefGuideExamplesTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Test
public void queryWithRawSolrParamsExample() throws Exception {
  expectLine("Found 3 documents");
  expectLine("id: 1; name: Fitbit Alta");
  expectLine("id: 2; name: Sony Walkman");
  expectLine("id: 3; name: Garmin GPS");
  
  // tag::solrj-query-with-raw-solrparams[]
  final SolrClient client = getSolrClient();

  final Map<String, String> queryParamMap = new HashMap<String, String>();
  queryParamMap.put("q", "*:*");
  queryParamMap.put("fl", "id, name");
  queryParamMap.put("sort", "id asc");
  MapSolrParams queryParams = new MapSolrParams(queryParamMap);

  final QueryResponse response = client.query("techproducts", queryParams);
  final SolrDocumentList documents = response.getResults();

  print("Found " + documents.getNumFound() + " documents");
  for(SolrDocument document : documents) {
    final String id = (String) document.getFirstValue("id");
    final String name = (String) document.getFirstValue("name");
    
    print("id: " + id + "; name: " + name);
  }
  // end::solrj-query-with-raw-solrparams[]
}
 
Example #29
Source File: SolrOntologyHelperFactoryTest.java    From BioSolr with Apache License 2.0 5 votes vote down vote up
@Test
public void construct_missingOLSOntology() throws Exception {
	Map<String, String> paramMap = new HashMap<>();
	paramMap.put(SolrOntologyHelperFactory.OLS_BASE_URL, "http://www.ebi.ac.uk/ols/beta/api");
	SolrOntologyHelperFactory factory = new SolrOntologyHelperFactory(new MapSolrParams(paramMap));
	OntologyHelper helper = factory.buildOntologyHelper();
	assertTrue(helper instanceof OLSTermsOntologyHelper);
}
 
Example #30
Source File: SolrOntologyHelperFactoryTest.java    From BioSolr with Apache License 2.0 5 votes vote down vote up
@Test
public void buildOntologyHelper_ols() throws Exception {
	Map<String, String> paramMap = new HashMap<>();
	paramMap.put(SolrOntologyHelperFactory.OLS_BASE_URL, "http://www.ebi.ac.uk/ols/beta/api");
	paramMap.put(SolrOntologyHelperFactory.OLS_ONTOLOGY_NAME, "efo");
	SolrOntologyHelperFactory factory = new SolrOntologyHelperFactory(new MapSolrParams(paramMap));
	OntologyHelper helper = factory.buildOntologyHelper();
	assertTrue(helper instanceof OLSOntologyHelper);
}