How to query using CloudSorlServer - java

I have a problem when I want to query from my java web service into solr server. My code looks like this:
CloudSolrServer solr = new CloudSolrServer("BigDataNew1:2181,BigDataNew2:2181,BigDataNew3:2181,BigDataNew4:2181,BigDataNew5:2181/solr");
Solr Queryquery = new SolrQuery();
ModifiableSolrParams param = new ModifiableSolrParams();
param.set("q",keyword).set("fl"," id, title, desc, pubDate, media, person, location").set("count","1").set("wt", "json").set("facet", true).set("start", "0").set("rows", "5");
QueryResponse response = solr.query(param);
SolrDocumentList list = response.getResults();
I got the following error:org.apache.solr.client.solrj.SolrServerException: No collection param specified on request and no default collection has been set.
Anybody know what the problem is?
Thanks

You'll need to tell CloudSolrServer which collection you want to query.
You can do this by setting it with setDefaultCollection:
solr.setDefaultCollection("foobar");

Related

Querying to get the ObjectID of the Project through Rally Rest API in java

Am trying with the below code to get the ObjectID of the Project by using Project's FormattedID...but am getting no results. Please let me know, where am getting wrong.
String projectFormattedID = "EH-HELLO-WORLD";
QueryRequest projectRequest = new QueryRequest("project");
storyRequest.setFetch(new Fetch("ObejctID"));
storyRequest.setQueryFilter(new QueryFilter("FormattedID", "=", projectFormattedID));
QueryResponse storyQueryResponse = restApi.query(storyRequest);
System.out.println(storyQueryResponse.getResults());
Looks like you have a typo in your fetch. It should be:
storyRequest.setFetch(new Fetch("ObjectID"));
Also, you can always get the ObjectID by parsing it out of the _ref attribute, which is always rendered on all responses:
String objectId = Ref.getOidFromRef(storyObject.get("_ref").getAsString());

elastic search query in java

I am having trouble making this URL query work in Java, it does not return any results. but from the browser it returns all the results, here is the URL that returns result:
_search?pretty&q=*357*+AND+account_id:574fe92c9179a809fd76f0b8+AND+invalid:false
And here is my code (does not return any results):
FilterBuilder[] filtersArray = new FilterBuilder[2];
filtersArray[0] = FilterBuilders.termFilter("account_id", "574fe92c9179a809fd76f0b8");
filtersArray[1] = FilterBuilders.termFilter("invalid", false);
QueryBuilder query = QueryBuilders.filteredQuery(QueryBuilders.simpleQueryStringQuery("*357*"), FilterBuilders.andFilter(filtersArray));
SearchResponse response = esClient.prepareSearch(SecurityManager.getNamespace())
.addSort("created_time", SortOrder.DESC)
.setTypes(dataType)
.setQuery(query)
.addFields("_id")
.setFrom(page * size)
.setSize(size)
.setExplain(false)
.execute()
.actionGet();
Can someone tell me what is the best way to translate the URL query into a java query?
First off, the URL query you should use is this one
?q=*357*+AND+account_id:574fe92c9179a809fd76f0b8+AND+invalid:false
otherwise you'll have no constraint on account_id and invalid
Then, the exact translation of this new URL query in Java is
QueryBuilder query = QueryBuilders.queryStringQuery("*357* AND account_id:574fe92c9179a809fd76f0b8 AND invalid:false");
SearchResponse response = esClient.prepareSearch(SecurityManager.getNamespace())
.addSort("created_time", SortOrder.DESC)
.setTypes(dataType)
.setQuery(query)
.addFields("_id")
.setFrom(page * size)
.setSize(size)
.setExplain(false)
.execute()
.actionGet();
Notes:
queryStringQuery and not simpleQueryStringQuery
no filters as they are all in the query string already

Correct use case of String parameter in SetQuery function of SolrQuery?

I have q
queryString = "select?wt=json&rows=0&indent=true&facet=true&q=*:*&facet=true&facet.field=outcome_type"
If queried like :
http://x.x.x.x:8983/solr/abc/queryString
it works. here abc is a core.
Now I would like to execute it programmatically, and using the following approach :
SolrQuery query = new SolrQuery();
query.setQuery(queryString);
QueryResponse resp = server.query(query);
here queryString as defined above, but it return the following error :
Exception in thread "main"
org.apache.solr.client.solrj.impl.HttpSolrServer$RemoteSolrException:
undefined field text
What I am missing here ? Or I need to build the query by set functions ?
I see few problems in your tentative.
You should not pass entire query string with the setQuery method. For almost each parameter available in query string there is a corresponding method in SolrQuery class.
SolrQuery does not support json format, SolrJ only supports the javabin and xml formats, I suggest to not specify any wt parameter.
So, you should use setQuery method only for q parameter:
query.setQuery("*:*");
For remaining parameters, the easiest way is use add method:
query.add("rows", "0"); // instead of setRows(0)
query.add("indent", "true");
query.add("facet", "true"); // ... setFacet(true)
query.add("facet.field", "outcome_type"); // ... addFacetField("outcome_type")
Hope this helps
I have used following approach to execute the query and it worked:
SolrQuery query = new SolrQuery();
query.setQuery(queryString);
query.setFacet(true);
query.set("wt", "json");
query.set("indent",true);
query.setRows(0);
query.addFacetField("outcome_type");
QueryResponse resp = server.query(query);

Java driver: how to get the objectId of an updated object with Mongodb's updateFirst method

I'm trying to get the objectId of an object that I have updated - this is my java code using the java driver:
Query query = new Query();
query.addCriteria(Criteria.where("color").is("pink"));
Update update = new Update();
update.set("name", name);
WriteResult writeResult = mongoTemplate.updateFirst(query, update, Colors.class);
Log.e("object id", writeResult.getUpsertedId().toString());
The log message returns null. I'm using a mongo server 3.0 on mongolab as I'm on the free tier so it shouldn't return null. My mongo shell is also:
MongoDB shell version: 3.0.7
Is there an easy way to return the object ID for the doc that I have just updated? What is the point of the method getUpsertedId() if I cannot return the upsertedId?
To do what I want, I currently have to issue two queries which is highly cumbersome:
//1st query - updating the object first
Query query = new Query();
query.addCriteria(Criteria.where("color").is("pink"));
Update update = new Update();
update.set("name", name);
WriteResult writeResult = mongoTemplate.updateFirst(query, update, Colors.class);
//2nd query - find the object so that I can get its objectid
Query queryColor = new Query();
queryColor.addCriteria(Criteria.where("color").is("pink"));
queryColor.addCriteria(Criteria.where("name").is(name));
Color color = mongoTemplate.findOne(queryColor, Color.class);
Log.e("ColorId", color.getId());
As per David's answer, I even tried his suggestion to rather use upsert on the template, so I changed the code to the below and it still does not work:
Query query = new Query();
query.addCriteria(Criteria.where("color").is("pink"));
Update update = new Update();
update.set("name", name);
WriteResult writeResult = mongoTemplate.upsert(query, update, Colors.class);
Log.e("object id", writeResult.getUpsertedId().toString());
Simon, I think its possible to achieve in one query. What you need is a different method called findAndModify().
In java driver for mongoDB, it has a method called findOneAndUpdate(filter, update, options).
This method returns the document that was updated. Depending on the options you specified for the method, this will either be the document as it was before the update or as it is after the update. If no documents matched the query filter, then null will be returned. Its not required to pass options, in that case it will return the document that was updated before update operation was applied.
A quick look at the mongoTemplate java driver docs here: http://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/core/FindAndModifyOptions.html tells me that you can use the method call:
public <T> T findAndModify(Query query,
Update update,
FindAndModifyOptions options,
Class<T> entityClass)
You can also change the FindAndModifyOptions class to take on an 'upsert' if the item was not found in the query.If it is found, the object will just be modified.
Upsert only applies if both
The update options had upsert on
A new document was actually created.
Your query neither has upsert enabled, nor creates a new document. Therefore it makes perfect sense that the getUpsertedId() returns null here.
Unfortunately it is not possible to get what you want in a single call with the current API; you need to split it into two calls. This is further indicated by the Mongo shell API for WriteResults:
The _id of the document inserted by an upsert. Returned only if an
upsert results in an insert.
This is an example to do this with findOneAndUpdate(filter,update,options) in Scala:
val findOneAndUpdateOptions = new FindOneAndUpdateOptions
findOneAndUpdateOptions.returnDocument(ReturnDocument.AFTER)
val filter = Document.parse("{\"idContrato\":\"12345\"}")
val update = Document.parse("{ $set: {\"descripcion\": \"New Description\" } }")
val response = collection.findOneAndUpdate(filter,update,findOneAndUpdateOptions)
println(response)

Can We Pass Multiple Parameters to RestCypherQueryEngine.query?

I want to implement a log in portal using java, neo4j REST API and Spring Framework. I am using the RestCypherQueryEngine class to send a cypher query to the server.
The query looks like -->
String query = "MATCH n WHERE n.Email = {email} AND n.Password = {pass} RETURN n;"
final QueryResult<Map<String,Object>> result = engine.query(query, Map.Util("Email", email), Map.Util("Password", pass);
.
"email" and "pass" are both Strings with the respective values.
I wanted to know if this is a valid query and can two parameters be passed like this ?
and how to know if a node has been returned or not or if the the login is authenticated. ?
Thank you.
You need to put all parameters into one map:
Map<String,Object> params = new HashMap<>();
params.put("email", email");
params.put("password", pass);
QueryResult<Map<String,Object>> result = engine.query(query,params);
NB: Query parameters are case sensitive.

Categories

Resources