Solr: Retrieving the query from a QueryResponse - solr

Given a QueryResponse object (SolrJ 3.6.2), is there any way to retrieve the query that was made to get that response other than parsing the query string?

QueryResponse exposes the Header information from which the q can be retrieved.
rsp.getHeader().get("q")

QueryResponse exposes the Header information from which the q can be retrieved. But it cant be directly retrived directly as mentioned by Jayendra.
You need to use:
response.getHeader().get("params");
This will give you a result like:
{start=0,q=apple,qf=name^10.0 description^5.0,version=2,rows=10,defType=edismax}
There you can see your result.

Related

query data in a airtable database using url

I want to implement URL for search specific data in my base using filterByFormula
below are my link and I got an error and how to resolve that
my url:
api.airtable.com/v0/APPID/Stories?filterByFormula=(FIND(“Car (in robot form) will offer a hug when I am stressed out”,{User want}) &api_key=MYKEY
Error :
{
"error": {
"type": "INVALID_FILTER_BY_FORMULA",
"message": "The formula for filtering records is invalid: Invalid formula. Please check your formula text."
}
}
I tried using postman, please help me.
While querying filtered data from Airtable via API, you don't have to use FIND keyword. You can filter data with simple Airtable formula like structure. For example,
{Email} = 'johnwick#neverdie.com'
Above filter retrieve all the records from the table whose Email is simply johnwick#neverdie.com
To limit number of records retrieve by API maxRecord parameter is available for that. For more info about various parameters please refer my answer here AirTable API Find record by email or official Airtable API Documentation
In your case
API url would be structured like,
api.airtable.com/v0/APPID/Stories?filterByFormula=Car+(in+robot+form)+will+offer+a+hug+when+I+am+stressed+out%3D%22User+want%22&api_key=MYKEY
For more info about Airtable API encoding, check this https://codepen.io/airtable/full/rLKkYB?baseId=app1C5TVoophmmr8M&tableId=tblvILr4aSAYI98oa
Hope this helps!

POST json request to Solr with cursorMark in request

Is it possible to include cursorMark value in POST request's body instead of sending it as query string parameter?
The following query:
{"query":"val:abc","limit":10,"cursorMark":"*","sort":"id asc"}
returns an error with the message: "Unknown top-level key in JSON request : cursorMark"
According to Solr Json Request API documentation, every query string parameter has a corresponding POST request parameter in JSON API, e.g. q -> query, start -> offset, etc.
However, there is no equivalent parameter for cursorMark query string parameter.
The best solution I am aware of is changing request type from application/json to application/x-www-form-urlencoded which allows using query string parameters in POST request's body. The reason why I was using application/json was to get json response, but it turns that it is controlled by wt=json parameter.
Changed query uri to: http://localhost:8983/solr/myCore/select?wt=json
Changed POST request parameters back to query string counterparts, i.e. q, start, rows, etc.
UrlEncoded the query string.
Put the encoded query string in POST body.
Changed request content type to application/x-www-form-urlencoded.
https://solr.apache.org/guide/7_7/json-request-api.html#passing-parameters-via-json says that you can augment a JSON-based POST with non-JSON params. I got this to work in 2022 with a JSON query that includes "params": {"cursorMark": "*"}, without needing to resort to changing the request type (as suggested in the accepted answer).

solrj RealTime get

How can I execute a RealTime get request from the SolrJ client?
I specifically need to retrieve un-commited documents in order to check the _version_ field for optimistic concurrency.
Since the RealTime Get is implemented with an alternate requestHandler, you would just need to use the setRequestHandler() method on SolrQuery passing "/get" as the handler name.
Please see the testRealTimeGet() method in this SolrExampleTests.java file from the Solr source for a full example.
Here is the snippet from that file:
SolrQuery q = new SolrQuery();
q.setRequestHandler("/get");
q.set("id", "DOCID");
q.set("fl", "id,name,aaa:[value v=aaa]");

quoted format json from Solrj

It looks like the QueryResponse from Solrj has no mean to give you a quoted Json string with wt=on or not. All I received is something like this
{responseHeader={status=0,QTime=2,params= {fl=id,productName,imageFront,priceEng,priceEngExp...
Question:
1) Am I missing something here ? Or there is no way to get the json response properly from the Solr server by Solrj.
2) Now on my client, if I convert the non-quoted json string from Solrj, does it mean it was done two times, once in server time and one in the Solrj client time ?
You can get JSON response by setting wt=json to the Solr query. Example URL is shown below :
localhost:8983/solr/select/?q=:&rows=10&indent=on&wt=json
You can't get JSON response using Solrj. You don't need to use Solrj for this purpose.By sending HTTP requests to the URL above, you can get json response.
With newer versions of Solr (starting with 4.7.0) it is possible to return the query response directly in json-format. This can be done with the NoOpResponseParser.
SolrQuery query = new SolrQuery();
QueryRequest req = new QueryRequest(query);
NoOpResponseParser rawJsonResponseParser = new NoOpResponseParser();
rawJsonResponseParser.setWriterType("json");
req.setResponseParser(rawJsonResponseParser);
NamedList<Object> resp = mySolrClient.request(req);
String jsonResponse = (String) resp.get("response");
System.out.println(jsonResponse );

How can i extract attachments from salesforce?

I need to extract attatchments out of salesforce? I need to transfer some notes and attachments into another environmant. I am able to extract the notes but not sure how to go about extracting the attatchments
Thanks
Prady
This mostly depends on what tools/utilities you use to extract. The SOQL for Attachment sObject will always return one row at a time if Body field is included in the query. This is enforced to conserver resources and prevent overbearing SOQL scripts.
Approach #1, if queryMore is not available: Issue a SOQL without Body field to enumerate all attachments, then issue one SOQL per attachment ID to retrieve Body
Approach #2: Issue a SOQL to retrieve all needed attachments then loop using queryMore to get them one at a time.
Approach #3: If you can "freeze" the SF environment and just want to take snapshot of the system to pre-load a different one to be used going forward you can use "data exports". In setup menu, in data management there is an export data command, make sure you click "Include in export" to include all binary data. After due process it will give you a complete data backup you can crunch offline.
Btw, body is base64 encoded, you'll need to decode it to get the actual binary
Here is the solution I've used to get the attachment binary content from SalesForce. The example in their documentation points the following:
curl
https://na1.salesforce.com/services/data/v20.0/sobjects/Document/015D0000000NdJOIA0/body
-H "Authorization: Bearer token"
So there are a couple different elements here. The host (https://na1.salesforce.com) you should be able to get after the login process, this host is session based so it can always change. Second element is the rest of the URL, that you will get from the "body" field of the Attachment object. Third and last element is the Authorization header, which is composed by the string "Bearer ", plus the token that is given to you after you authenticate with the SF backend.
The response is the binary file, it is NOT in base64, just save it to a file and you are good to go.
Here is an example of how I did it in Objective C:
// How to get the correct host, since that is configured after the login.
NSURL * host = [[[[SFRestAPI sharedInstance] coordinator] credentials] instanceUrl];
// The field Body contains the partial URL to get the file content
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#", [host absoluteString], {AttachmentObject}.body]];
// Creating the Authorization header. Important to add the "Bearer " before the token
NSString *authHeader = [NSString stringWithFormat:#"Bearer %#",[[[[SFRestAPI sharedInstance] coordinator] credentials] accessToken]];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0];
[urlRequest addValue:authHeader forHTTPHeaderField:#"Authorization"];
[urlRequest setHTTPMethod:#"GET"];
urlConnection = [NSURLConnection connectionWithRequest:urlRequest delegate:self];
Hope it helps.
You can use SOQl Query options, or if you are looking for some automation tool that will help you with quick export, then you can try AppExchange App Satrang Mass File Download - https://appexchange.salesforce.com/listingDetail?listingId=a0N3A00000EcsAOUAZ&tab=e
Disclaimer: I work at Satrang Technologies, the publisher of this Mass File Download AppExchange App.
In SalesForce attachment will be against an Object for e.g. Account object.
Steps to retrieve attachment (in Java)
Get the ID of the Object to which a file is attached. e.q. Account Object
String pid = Account__r().getId();
Execute a Query on Salesforce Object "Attachment" for the ID in Step 1
*String q = "Select Name, Body, ContentType from Attachment
where ParentId = '" + pid + "'";
QueryResult qr = connection.query(q);
SObject[] sarr = qr.getRecords();*
SObject so = sarr[0];
Typecast Salesforce Generic Object (SObject) to "Attachment" object
*Attachment att = (Attachment)so;*
Retrieve the Byte Array Stream from Body of Attachment, and do the operation needed on byte array.
*byte[] bName = att.getBody();
// Do your operation in byte array stream*

Resources