How to get the suggested terms from Solr suggester response [duplicate] - java

What is the correct way of getting results from solrj using Solr Suggester?
This is my request:
SolrQuery query = new SolrQuery();
query.setRequestHandler("/suggest");
query.setParam("suggest", "true");
query.setParam("suggest.build", "true");
query.setParam("suggest.dictionary", "mySuggester");
query.setParam("suggest.q", "So");
QueryResponse response = server.query(query);
However I found it extremely difficult to get the response. The way I got the response is with this:
NamedList obj = (NamedList)((Map)response.getResponse().get("suggest")).get("mySuggester");
SimpleOrderedMap obj2 = (SimpleOrderedMap) obj.get("So");
List<SimpleOrderedMap> obj3 = (List<SimpleOrderedMap>) obj2.get("suggestions");
This seems to assume a lot about the objects I am getting from the response and will be difficult to anticipate errors.
Is there a better and cleaner way than this?

In new versions have a SuggesterResponse:
https://lucene.apache.org/solr/5_3_1/solr-solrj/org/apache/solr/client/solrj/response/SuggesterResponse.html

Best option is to get it as List, below code worked for me
HttpSolrClient solrClient = new HttpSolrClient(solrURL);
SolrQuery query = new SolrQuery();
query.setRequestHandler("/suggest");
query.setParam("suggest.q", "Ins");
query.setParam("wt", "json");
try {
QueryResponse response = solrClient.query(query);
System.out.println(response.getSuggesterResponse().getSuggestedTerms());
List<String> types=response.getSuggesterResponse().getSuggestedTerms().get("infixSuggester");
System.out.println(types);
} catch (SolrServerException | IOException e) {
e.printStackTrace();
}

You can get the suggestions via the SpellCheckResponse by doing the following
SpellCheckResponse spellCheckResponse=response.getSpellCheckResponse();
Check this link for more details

Related

How to get a suggestion through solrTemplate

When using solrTemplate, I have no way to get the results in suggest. With solrj I can use getSuggesterResponse() to get this result.
I debugged it and found that it didn't use getSuggesterResponse() to get the suggest.
solrj
HttpSolrClient httpSolrServer = SolrUtil.createSolrServer();
SolrQuery solrQuery = new SolrQuery();
solrQuery.set("qt", "/suggest");
solrQuery.setQuery("mm");
QueryResponse response = httpSolrServer.query(solrQuery);
SuggesterResponse suggesterResponse = response.getSuggesterResponse();
Map<String, List<String>> suggestedTerms =
suggesterResponse.getSuggestedTerms();
List<String> terms = suggestedTerms.get("suggest");
solrTemplate:
TermsQuery query = new SimpleTermsQuery();
query.setRequestHandler("/suggest");
query.addCriteria(new Criteria().is("mm"));
TermsPage terms = solrTemplate.queryForTermsPage("core2", query);
I checked all the documentation, but I didn't find a way.
I think solrTemplate has no native support for suggest.
But you can use solrJ inside of solrTemplate
SolrQuery q = new SolrQuery();
q.setRequestHandler("/suggest");
q.setParam("suggest.q", searchTerm);
q.setParam("suggest", "true");
q.setParam("suggest.dictionary", "mySuggester");
q.setParam("suggest.build", "true");
QueryResponse queryResponse = solrTemplate.execute(solrClient -> solrClient.query("collectionName", q));
SuggesterResponse suggesterResponse = queryResponse.getSuggesterResponse();

How to execute searchAndRank method in IBM Watson Retrieve And Rank API through Java wrapper

I am trying to perform a retrieveAndRank query using Java wrapper. I follow the online javadocs for Retrieve and Rank API.
The example there for SearchAndRank is:
https://www.ibm.com/watson/developercloud/retrieve-and-rank/api/v1/#query_ranker
RetrieveAndRank service = new RetrieveAndRank();
service.setUsernameAndPassword("{username}","{password}");
HttpSolrClient solrClient = new HttpSolrClient;
solrClient = getSolrClient(service.getSolrUrl("scfaaf8903_02c1_4297_84c6_76b79537d849"), "{username}","{password}");
SolrQuery query = new SolrQuery("what is the basic mechanism of the transonic aileron buzz");
QueryResponse response = solrClient.query("example_collection", query);
Ranking ranking = service.rank("B2E325-rank-67", response);
System.out.println(ranking);
but RetrieveAndRank class has no such rank(String rankerId, QueryResponse response) method. Just one getting a file or an InputStream as arguments (browsing IBM’s source code I see it expects CSV content not a java QueryResponse there).
How should I pass QueryResponse to the rank method?
I am using solr-solrj-5.5.2.jar and java-sdk-3.2.0-jar-with-dependencies.jar libraries
You need to use the /fcselect query handler and send the ranker_id as a parameter.
The code below assumes you have a Solr collection with documents and you have trained a ranker, otherwise follow this tutorial.
RetrieveAndRank service = new RetrieveAndRank();
service.setUsernameAndPassword(USERNAME, PASSWORD);
// create the solr client
String solrUrl = service.getSolrUrl(SOLR_CLUSTER_ID);
HttpClient client = createHttpClient(solrUrl, USERNAME, PASSWORD);
HttpSolrClient solrClient = new HttpSolrClient(solrUrl, client);
// build the query
SolrQuery query = new SolrQuery("*:*");
query.setRequestHandler("/fcselect");
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!");
System.out.println(response);
Make sure you update the service credentials for RetrieveAndRank(USERNAME and PASSWORD), SOLR_CLUSTER_ID, SOLR_COLLECTION_NAME and RANKER_ID.
The code for createHttpClient() can be found here.

Rally API, Creating Test Case Result - Connection Closed Exception

I'm developing in java / groovy and am new to the Rally API, I begun using it last week. I want to be able to use the REST API to create a new Test Case Result. On friday (its monday when I wrote this), I got it working using the example below, putting in the data I wanted using arguments into the method. I found this example on another website.
Today when I ran the code, and I dont think I changed anything, I keep getting "ConnectionClosedException: Premature end of Content-Length delimited message body (expected: 1390; received: 1389).
I rewrote the code again, this time not changing anything from the example just to try and get it working again, and I get the same exception. Heres the code I'm using:
public static void createTestCaseResults(){
// Create and configure a new instance of RallyRestApi
RallyRestApi restApi = new RallyRestApi(new URI("https://rally1.rallydev.com"),"username#company.com", "Password");
restApi.setWsapiVersion("1.36");
restApi.setApplicationName("Add Test Case Result");
//Query User
QueryRequest userRequest = new QueryRequest("User");
userRequest.setFetch(new Fetch("UserName", "Subscription", "DisplayName"));
userRequest.setQueryFilter(new QueryFilter("UserName", "=", "username#company.com"));
QueryResponse userQueryResponse = restApi.query(userRequest);
JsonArray userQueryResults = userQueryResponse.getResults();
JsonElement userQueryElement = userQueryResults.get(0);
JsonObject userQueryObject = userQueryElement.getAsJsonObject();
String userRef = userQueryObject.get("_ref").getAsString();
// Query for Test Case to which we want to add results
QueryRequest testCaseRequest = new QueryRequest("TestCase");
testCaseRequest.setFetch(new Fetch("FormattedID","Name"));
testCaseRequest.setQueryFilter(new QueryFilter("FormattedID", "=", "TC7562"));
QueryResponse testCaseQueryResponse = restApi.query(testCaseRequest);
JsonObject testCaseJsonObject = testCaseQueryResponse.getResults().get(0).getAsJsonObject();
String testCaseRef = testCaseQueryResponse.getResults().get(0).getAsJsonObject().get("_ref").getAsString();
try{
//Add a Test Case Result
System.out.println("Creating Test Case Result...");
JsonObject newTestCaseResult = new JsonObject();
newTestCaseResult.addProperty("Verdict", "Pass");
newTestCaseResult.addProperty("Date", "2012-06-12T18:00:00.000Z");
newTestCaseResult.addProperty("Notes", "Automated Selenium Test Runs");
newTestCaseResult.addProperty("Build", "2012.05.31.0020101");
newTestCaseResult.addProperty("Tester", userRef);
newTestCaseResult.addProperty("TestCase", testCaseRef);
CreateRequest createRequest = new CreateRequest("testcaseresult", newTestCaseResult);
CreateResponse createResponse = restApi.create(createRequest);
if(createResponse.wasSuccessful()){
println(String.format("Created %s", createResponse.getObject().get("_ref").getAsString()));
//Read Test Case
String ref = Ref.getRelativeRef(createResponse.getObject().get("_ref").getAsString());
System.out.println(String.format("\nReading Test Case Result %s...", ref));
GetRequest getRequest = new GetRequest(ref);
getRequest.setFetch(new Fetch("Date", "Verdict"));
GetResponse getResponse = restApi.get(getRequest);
JsonObject obj = getResponse.getObject();
println(String.format("Read Test Case Result. Date = %s, Verdict = %s", obj.get("Date").getAsString(), obj.get("Verdict").getAsString()));
} else {
String[] createErrors;
createErrors = createResponse.getErrors();
System.out.println("Error occurred creating Test Case: ");
for (int i=0; i<createErrors.length;i++) {
System.out.println(createErrors[i]);
}
}
}
finally{
restApi.close()
}
}
Appreciate any help with this. Thanks. :)
Is this still happening for you today? I just tried your code on both rally1 and our demo system, and it works reliably every time (only changed username and password, and the test case formatted id).
As a possible next step, I'd set a breakpoint in RallyRestApi.doRequest where the server response code is checked and see what additional information was available - for example, the response code, and the body and headers for the response.
This very well may be a bug in the underlying Apache HttpComponents library. I just upgraded to the latest 4.2.1 components. Would you mind giving the new 1.0.2 jar a try?
https://github.com/RallyTools/RallyRestToolkitForJava
Update:
This has been fixed with the 1.0.4 release of the toolkit today:
https://github.com/downloads/RallyTools/RallyRestToolkitForJava/rally-rest-api-1.0.4.jar

How to set ResponseWriter to non-default in Solr

I have the following code, which is simply searching the Solr Server.
SolrServer server = new CommonsHttpSolrServer(url);
SolrQuery searchquery = new SolrQuery("company profile");
QueryResponse response = server.query(searchquery)
I want to have the response in json, other than the default which is xml. So I went into the solrconfig.xml file and enabled the following line:
<queryResponseWriter name="json" class="org.apache.solr.request.JSONResponseWriter" />
However, from the console, I'm still getting wt=javabin encoded to the search query request.
Also, I've modified the above code like this:
SolrServer server = new CommonsHttpSolrServer(url);
SolrQuery searchquery = new SolrQuery("company profile");
searchquery.setParam("wt", "json");
QueryResponse response = server.query(searchquery)
But I'm still getting wt=javabin encoded and wt=json also appended, such that the query now looks like this:
webapp/solr path=/select params={wt=javabin&wt=json}
Is there anything I'm doing wrong?
Thanks
SolrJ only supports the javabin and xml formats (configurable with CommonHttpSolrServer.setParser).
But why would you want to use JSON? Javabin is by far the format which provides the best decompression speed, its drawback being that is is not human-readable, on the contrary to JSON and XML (which is not a problem in this case since SolrJ is parsing the result for you).
With SolrJ and json-lib, I was able to get json response like this:
SolrServer server = new CommonsHttpSolrServer(url);
SolrQuery searchquery = new SolrQuery("company profile");
QueryResponse response = server.query(searchquery)
JSONArray jsonObject = JSONArray.fromObject( response.getResults() );
log.log(Level.INFO, "received jsonObject is {0}", jsonObject.toString());
Iterator data = jsonObject.iterator();
SolrResultBean bean = new SolrResultBean();
List output = new ArrayList();
while(data.hasNext()) {
output.add(data.next());
}
log.log(Level.INFO, "json items in the List are {0}", output);
bean.setObject(output);
// wicket page redirect
setResponsePage(SearchPage.class, new PageParameters());

How to use SpellingResult class in SolrJ

I'm using SolrJ. But through the API documentation could not figure out how to use the particular class to receive the response of the spell checker.
i have a search component defined in solrconfig.xml for performing the checking
Maybe you already found the solution, anyway the SpellingResult class comes with Solr, while you're using SolrJ to access a Solr server, if I'm not wrong. So, you should use the specific classes that come with SolrJ; the QueryResponse object contains a SpellCheckResponse object with all the information you're looking for.
SolrServer solr = new CommonsHttpSolrServer("http://localhost:8080/solr");
ModifiableSolrParams params = new ModifiableSolrParams();
params.set("qt", "/spell");
params.set("q", "whatever");
params.set("spellcheck", "on");
//params.set("spellcheck.build", "true");
QueryResponse response = solr.query(params);
SpellCheckResponse spellCheckResponse = response.getSpellCheckResponse();
if (!spellCheckResponse.isCorrectlySpelled()) {
for (Suggestion suggestion : response.getSpellCheckResponse().getSuggestions()) {
logger.debug("original token: " + suggestion.getToken() + " - alternatives: " + suggestion.getAlternatives());
}
}
Hope this helps.

Categories