How to get full explanation of Elasticsearch query Java? - java

I'm currecntly trying to test out some new score functions on my Elasticsearch query but I'm not yielding the results I am expecting.
I found this on their site about explaining queries here
I can run as a curl command but does anyone know how to translate this to use the Java api?

If you're using the ES5 Java API, you can get the explanation like this:
QueryBuilder query = matchAllQuery(); // your query
ExplainRequest request = new ExplainRequest("index", "type", "id").query(query);
ExplainResponse explainResponse = client.explain(request).actionGet();
Explanation explanation = explainResponse.getExplanation();
Where client is your org.elasticsearch.client.Client instance.

Related

Datastore query with IN operator

The new flexible environment datastore interface does not seem to support IN operation when running a query. I hope that I'm wrong, and if so, how can one use an IN operator in the new Java interface of Datastore?
A query like - WHERE color IN('RED', 'BLACK'), it is not supported by the Datastore (server side). Same is the case with OR operator (e.g. WHERE color='RED' OR color='BLACK'). Some client APIs have added this functionality by splitting the query into multiple and then merging the results from each query. The new google-cloud-java API does not support this yet. For now, you would have to run multiple queries for each value in the IN clause and merge the results.
Here’s an example from the documentation:
If you want to set more than one filter on a query, you must use CompositeFilter, which requires at least two filters.
Filter tooShortFilter = new FilterPredicate("height", FilterOperator.LESS_THAN, minHeight);
Filter tooTallFilter = new FilterPredicate("height", FilterOperator.GREATER_THAN, maxHeight);
Filter heightOutOfRangeFilter = CompositeFilterOperator.or(tooShortFilter, tooTallFilter);
Query q = new Query("Person").setFilter(heightOutOfRangeFilter);
You can also use .and(). The code here is for Java 7. For Java 8 you can find a corresponding code in the documentation referenced above. I hope that helps.
Now to IN. While I have not tried it myself recently, the current documentation states that it can still be used as an operator. According to it, something like the code below should work:
Filter propertyFilter = new FilterPredicate("height", FilterOperator.IN, minHeights);
Query q = new Query("Person").setFilter(propertyFilter);
Alternatively, you could use Google GQL. It will allow you to write SQL-like syntax, in which you can use in(...).
I tried using the repository query methods, but I got an error informing that it is not supported.
Only solved for me using the #Query annotation;
Example:
#Query("select * from UserGroup where name IN #names")
List<Company> findAllByName(List<String> names);

writing a basic n1ql query in java

I have just started learning Couchbase. I am trying to write a basic query using java sdk but I am not able to understand how to write it. Below is the query:
SELECT *
FROM users_with_orders usr
JOIN orders_with_users orders
ON KEYS ARRAY s.order_id FOR s IN usr.shipped_order_history END
This is for joining without array:
LetPath path = select("*,META(usr).id as _ID,META(usr).cas as _CAS).from(bucketName +" usr").join(bucketname +" orders").onKeys("usr.order_id)
How should I proceed with the above query for on keys array?
Thanks!!!!
As described in the docs on Querying from the SDK, you can use either a simple string with the Java SDK or use the DSL. For example:
// query with a simple string
System.out.println("Simple string query:");
N1qlQuery airlineQuery = N1qlQuery.simple("SELECT `travel-sample`.* FROM `travel-sample` WHERE name=\"United Airlines\" AND type=\"airline\"");
N1qlQueryResult queryResult = bucket.query(airlineQuery);
for (N1qlQueryRow result: queryResult) {
System.out.println(result.value());
}
//query with a parameter using the DSL
System.out.println("Parameterized query using the DSL:");
Statement statement = select(path(i("travel-sample"), "*")).from(i("travel-sample")).where(x("name").eq(x("$airline_param")).and(x("type").eq(s("airline"))));
JsonObject placeholderValues = JsonObject.create().put("airline_param", "United Airlines");
N1qlQuery airlineQueryParameterized = N1qlQuery.parameterized(statement, placeholderValues);
N1qlQueryResult queryResultParameterized = bucket.query(airlineQueryParameterized);
for (N1qlQueryRow row : queryResultParameterized) {
System.out.println(row);
}
(I posted a full gist of this example for the imports, etc.)
See the docs for more info, but you may want to use the DSL to allow IDE code completion and Java compile time checking. When developing an interactive web application, you'll probably also want to use parameterized statements (for security) and may even want prepared statements (for performance).

elasticsearch | template query | java API

I was trying to implement the feature of template query. Refer to the last section of http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-template.html
I added a query template using sense. Now the need is through JAVA API of elasticsearch, I need to execute this query template and store the result in SearchResponse. However I am not able to find any API related to query Template. The only class file which is available is TemplateQueryBuilder. This class constructs the template query perfectly but I am not sure of which method to be called from Client in order to pass the object of TemplateQueryBuilder.
Help in this is appreciated.
Here is how to do it :
SearchRequestBuilder request = client;.prepareSearch();
request.setTemplateName(templateName);
request.setTemplateType(ScriptService.ScriptType.INDEXED);
request.setTemplateParams(templateParams);
SearchResponse response = request.get();
You just need to parse the response object then ..
refer to: http://www.elasticsearch.org/guide/en/elasticsearch/client/java-api/current/search.html#java-search-template
Note that with API version 2.X, as request.setTemplateX methods are deprecated, you should use a different approach.
Either you can use request.setTemplate(Template template) which is similar to the accepted answer, or you can go with the more generic QueryBuilders approach:
QueryBuilder qb = QueryBuilders.templateQuery(
"templateName",
ScriptService.ScriptType.FILE,
templateParams);
More to read: https://www.elastic.co/guide/en/elasticsearch/client/java-api/2.4/java-specialized-queries.html#java-query-dsl-template-query

Solr returns same result after adding document with SolrJ

I am trying to get the results from a Solr query, doing a simple /select?q=id:xx
The problem is that its not returning anything when i use solr directly, but when i use SolrJ, like:
SolrQuery query = new SolrQuery();
query.setQuery(queryStr);
query.setRows(10);
QueryResponse rsp = solrServer.getSolrServer().query(query);
It returns the document added with no problem.
How is that possible, i was thinking perhaps the SolrJ its sending an extra parameter internally but i couldnt find it.
I am using Solr 4.2.1
After doing some test i solved the problem, i had to use HttpSolrServer, instead of EmbeddedSolrServer, it seems EmbeddedSolrServer use their own data somehow, so i was managing 2 different datas.
Using HttpSolrServer was the solution.

Search twitter by language

In twitter by using lang operator you can search for retrieving tweets from a particular language: For example, the following search will return tweets only in english:
https://twitter.com/search?q=lang:en
Is there a way to achieve this using twitter api, especially using twitter4j. I know there is a language attribute for search but it also requires at least one keyword to make a search, I would like to search by a particular language without giving any keyword query. The following command in java driver returns the following error:
Query searchQuery = new Query() //
.count(resultsPerPage) //
.since(since)//
.lang("en");
400:The request was invalid. An accompanying error message will explain why. This is the status code will be returned during version 1.0 rate limiting(https://dev.twitter.com/pages/rate-limiting). In API v1.1, a request without authentication is considered invalid and you will get this response.
message - Query parameters are missing
code - 25
Cheers
You must pass the same do you use in the twitter search, your query will be like:
new Query("lang:en")
Using twitter4j,
Query query = new Query();
query.setLang("en");
query.setQuery(searchQuery);

Categories