ibm-watson-cognitive Retrieve and Rank


The Solrj client and the Java SDK are independent so you can update them individually. Always make sure you use the latest version of the Java SDK.

See the GitHub release page for updates

Search and Rank using the Retrieve and Rank in Java

Install the required dependencies:


The code below assumes you have a Solr collection with documents and you have trained a ranker, otherwise follow this tutorial

public class RetrieveAndRankSolrJExample {

  private static HttpSolrClient solrClient;
  private static RetrieveAndRank service;

  private static String USERNAME = "<username>";
  private static String PASSWORD = "<password>";
  private static String SOLR_CLUSTER_ID = "<your-solr-cluster-id>";
  private static String SOLR_COLLECTION_NAME = "<your-collection-name>";
  private static String RANKER_ID = "<ranker-id>";
  public static void main(String[] args) throws SolrServerException, IOException {
    // create the retrieve and rank instance
    service = new RetrieveAndRank();
    service.setUsernameAndPassword(USERNAME, PASSWORD);

    // create the solr client
    String solrUrl = service.getSolrUrl(SOLR_CLUSTER_ID);
    solrClient = new HttpSolrClient(solrUrl, createHttpClient(solrUrl, USERNAME, PASSWORD));

    // build the query
    SolrQuery query = new SolrQuery("*:*");
    query.set("ranker_id", RANKER_ID);
    // execute the query
    QueryResponse response = solrClient.query(SOLR_COLLECTION_NAME, query);
    System.out.println("Found " + response.getResults().size() + " documents!");

  private static HttpClient createHttpClient(String uri, String username, String password) {
    final URI scopeUri = URI.create(uri);

    final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(scopeUri.getHost(), scopeUri.getPort()),
        new UsernamePasswordCredentials(username, password));

    final HttpClientBuilder builder = HttpClientBuilder.create()
        .addInterceptorFirst(new PreemptiveAuthInterceptor());

  private static class PreemptiveAuthInterceptor implements HttpRequestInterceptor {
    public void process(final HttpRequest request, final HttpContext context) throws HttpException {
      final AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE);

      if (authState.getAuthScheme() == null) {
        final CredentialsProvider credsProvider = (CredentialsProvider) context
        final HttpHost targetHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
        final Credentials creds = credsProvider.getCredentials(new AuthScope(targetHost.getHostName(),
        if (creds == null) {
          throw new HttpException("No creds provided for preemptive auth.");
        authState.update(new BasicScheme(), creds);