Hi,
i have created one saved search now i want to get the data from it. Give me some sample or example java code how to get data from saved search?
Thanks,
Veera.
4
Answers
getSavedSearch operation is used to retrieve a list of existing saved searches for each record type. Specify the search record type to get a list of record references of the saved search. Let´s focus on getSavedSearch webservices operation in netsuite.
getSavedSearch:
=======================
This operation allows users to retrieve a list of existing saved search IDs on a per-record-type basis (for example, all saved search IDs for every Customer saved search). Note that once you retrieve the list of saved search IDs, you may need to look in the NetSuite UI to see the criteria defined for the saved search. To navigate to the list of saved searches in the NetSuite UI, go to
Lists > Search > Saved Searches.
This API takes a search record type as a request argument and returns a list of record references of the saved search.
Note:
-----------------
There is no async equivalent for this operation.
Request:
--------------------------
The GetSavedSearchRequest type is used for the request. It contains the following fields.
1.record- Record(XSD Type) Contains an array of record objects. The record type is an abstract
type so an instance of a type that extends record must be used- such as Customer or Event.
Response:
------------------------------
The GetSavedSearchResponse type is used for the response. It contains the following fields.
1. status- Status(XSD Type) The status for this operation. All applicable errors or warnings are listed within this type.
2. totalRecords- xsd:int(XSD Type) The total number of records for this search. Depending on the pageSize value, some or all the records may be returned in this response
3. recordList- Record[](XSD Type) A list of records that correspond to the specified ids. The actual records returned need to be of a type that extends the abstract type Record.
Java Sample Code:
-----------------------------------------
public void getSavedSearches() throws RemoteException{
this.login(true);
GetSavedSearchRecord record = new GetSavedSearchRecord();
record.setSearchType(SearchRecordType.transaction);
GetSavedSearchResult result = _port.getSavedSearch(record);
}
Now i am going to give you an example of referencing Existing Saved Searches:
------------------------------------------------------------------------------------------------------------------------
Advanced search in Web services allows you to reference an existing saved search. Returning saved searches provides you with access to data that otherwise could not be returned in SuiteTalk. For example, advanced search allows you to return saved searches that include formula filters (in the search criteria) or expressions.
How do I reference an existing saved search?
--------------------------------------------------------------------------------
First must first obtain the saved search ID. You can do so through the UI by going to Lists > Search > Saved Searches. The saved search ID appears in the ID column.
You can also use the getSavedSearch operation to programmatically retrieve a list of saved search IDs for a specific record type. Note that this operation does nothing more than return a list of saved search IDs on a per-record-type basis (for example, all saved search IDs for the Customer record type).
You can then use the search() operation, along with the <Record>SearchAdvanced object to return the details of the saved search. The following is a simple example that shows how to instantiate the CustomerSearchAdvanced object and specify a savedSearchId to return.
// create search object
CustomerSearchAdvanced customerSearch = new CustomerSearchAdvanced();
//set saved search id
customerSearch.savedSearchId="100";
// perform the search
NetSuiteService nss = new NetSuiteService();
SearchResult result = nss.search(customerSearch);
Important: Note the following about saved searches in Web services:
------------------------------------------------------------------------------------------------------------------
1. Only one saved search can be referenced as part of the search call.
2. If you reference a saved search that contains search functions, you will get the results back. However, you cannot create an advanced search that uses search functions. Creating a search in Web services that uses search functions is not currently supported.
3. If you reference a saved search that contains summary results, you will get the following error:
We cannot return search columns for summary saved search <saved search ID>
Java Sample Code to Programmatically manipulate data returned by a search
------------------------------------------------------------------------------------------------------------------------
public void searchCustomerBySavedSearch() throws RemoteException {
this.login(true);
CustomerSearchAdvanced searchRecord = new CustomerSearchAdvanced();
searchRecord.setSavedSearchId("26"); // A saved customer search
SearchResult result = _port.search(searchRecord);
if( result.getTotalRecords() > 0 ) {
// retain the search ID in order to get more pages
String sSearchId = result.getSearchId();
SearchRowList rowList = result.getSearchRowList();
processRowList(rowList);
int iNumPages = result.getTotalPages();
for ( int i=2; i<=iNumPages; i++) {
result = _port.searchMoreWithId(sSearchId, i);
rowList = result.getSearchRowList();
processRowList(rowList);
}
}
}
public void processRowList(SearchRowList rowList) {
for (int i=0; i<rowList.getSearchRow().length; i++) {
CustomerSearchRow row = (CustomerSearchRow) rowList.getSearchRow(i);
CustomerSearchRowBasic basic = row.getBasic();
SearchColumnStringField companyName = basic.getCompanyName(0);
_console.write("Company Name: "+companyName.getSearchValue());
if (basic.getEmail(0).getSearchValue() != null) {
String email = basic.getEmail(0).getSearchValue();
_console.write("\tEmail: "+email);
}
if (basic.getPhone(0).getSearchValue() != null) {
String phone = basic.getPhone(0).getSearchValue();
_console.write("\tPhone: "+phone);
}
_console.writeLn("\n");
}
}
Searching for a Multi-select Custom Field:
--------------------------------------------------------------------------------------
In the following code sample, the results for the custom transaction field custcolcolumnname are returned.
Java Sample Code:
---------------------------------------
// transaction search by custom column field
TransactionSearchBasic transactionSearch = new TransactionSearchBasic();
SearchCustomFieldList searchCustomFieldList = new SearchCustomFieldList();
transactionSearch.setCustomFieldList(searchCustomFieldList);
// make the multiselectsearch
SearchMultiSelectCustomField searchMultiSelectCustomField = new SearchMultiSelectCustomField();
ListOrRecordRef listOrRecordRef = new ListOrRecordRef();
listOrRecordRef.setInternalId("3"); // the internal id of the custom list value
listOrRecordRef.setType("1"); // your custom list typeId
searchCustomFieldList.setCustomField(new SearchCustomField[]{searchMultiSelectCustomField});
// make the search expression
searchMultiSelectCustomField.setInternalId("custcolcolumnname"); //the name of the tx custom column
searchMultiSelectCustomField.setOperator(SearchMultiSelectFieldOperator.anyOf);
searchMultiSelectCustomField.setSearchValue(new ListOrRecordRef[] {listOrRecordRef});
SearchResult sr = _port.search(transactionSearch);
4
After creation of savedsearch do i need to do any changes/settings in netsuite?because while i´m trying to reference the saved search(as you mentioned above) getting field values as null.Getting successfully mysaved search name by using following code
GetSavedSearchRecord record = new GetSavedSearchRecord();
record.setSearchType(SearchRecordType.transaction);
GetSavedSearchResult result = _port.getSavedSearch(record);
RecordRefList rl= result.getRecordRefList();
RecordRef[] rf= rl.getRecordRef();
for(RecordRef rcf:rf){
System.out.println(rcf.getInternalId()+rcf.getName());
}
I think you didn´t read completely. i Think you should try second last sample code...
No i read it.After trying second last sample code i´m getting field value as null .with the 1st one we cant get fields data.
I think there may be problem same as described above in point 3 in important notes i.e. If you reference a saved search that contains summary results, you will get the following error: We cannot return search columns for summary saved search <saved search ID> .
In manipulating data by search record you´ll see that how to get data return by a search...
I didn´t get any exception in mystack trace.i´m getting size of records correctly.see below code,here getting null value(itemname/qty/customer)
for (int i=0; i<rowList.getSearchRow().length; i++) {
TransactionSearchRow ts=(TransactionSearchRow)rowList.getSearchRow(i);
TransactionSearchRowBasic tsb=ts.getBasic();
SearchColumnSelectField[] scsf=tsb.getItem();
for(SearchColumnSelectField sf:scsf){
RecordRef rf=sf.getSearchValue();
System.out.println("itemname:::"+rf.getName());
}
}
getSearchValue() returns a string. Get the value by index from SearchRowBasic and then call getSearchValue to get the value in String. Try below code:
tsb.getName(0).getSearchValue();
What i found was the saved search response returns only the internal id.Tested For item and customer fields getting internalIDs correctly.For getting values what i have to do?
System.out.println("itemname:::"+rf.getInternalID());
For the list type fields only have this problem(getting internalids),remaining fields amount,shipdate like these fields getting values succesfully.
Below is the code to Search the customer stage which is a list field. Now use these internal ids you are getting in this code..
Following is the java sample code that has both string and list search field. I hope it´d be helpful to you.
Java Code to Search Customer record with both String and List Field:
--------------------------------------------------------------------------------------------------------------------
public void searchCustomer() throws RemoteException,
ExceededUsageLimitFault, UnexpectedErrorFault, InvalidSessionFault,
ExceededRecordCountFault {
// This operation requires a valid session
this.login(true);
_console.writeLn("\nEnter search parameters");
// Instantiate a search object for customers. Note that the search
// object is different from the regular record used for add and update.
CustomerSearch custSearch = new CustomerSearch();
// Search the customer entity id which is a string field
_console.write("Entity ID (press enter to skip): ");
String nameValue = _console.readLn();
SearchStringField entityId = null;
if (!nameValue.equals("")) {
entityId = new SearchStringField();
entityId.setOperator(SearchStringFieldOperator.contains);
entityId.setSearchValue(nameValue);
custSearch.setEntityId(entityId);
}
// Search the customer stage which is a list field
_console
.write("Customer Stage (one or more nsKeys separated by commas, press enter to skip): ");
String stageKeysValue = _console.readLn();
SearchMultiSelectField stage = null;
if (!stageKeysValue.equals("")) {
stage = new SearchMultiSelectField();
stage.setOperator(SearchMultiSelectFieldOperator.anyOf);
String[] nskeys = stageKeysValue.split(",");
RecordRef[] recordRefs = new RecordRef[stageKeysValue.length()];
for (int i = 0; i < nskeys.length; i++) {
RecordRef recordRef = new RecordRef();
recordRef.setInternalId(nskeys[i]);
recordRefs[i] = recordRef;
}
stage.setSearchValue(recordRefs);
custSearch.setStage(stage);
}
if (custSearch.getEntityId() == null && custSearch.getStage() == null) {
_console
.info("\nNo search criteria was specified. Searching for all records.");
} else {
_console
.info("\nSearching for customers with the following criteria: "
+ (entityId == null ? ""
: ("\nentityId=" + custSearch
.getEntityId().getSearchValue())
+ ", Operator="
+ entityId.getOperator().toString())
+ (stage == null ? "" : ("\nstage nsKeys=´"
+ stageKeysValue + "´, Operator=" + stage
.getOperator().toString())));
}
// Set page size for number of records to be returned in search
// response
// Invoke search() web services operation
SearchResult result = _port.search(custSearch);
// Process result
if (result.getStatus().isIsSuccess()) {
// Process the records returned in the result and print to console
processCustomerSearchResponse(result);
// Since pagination controls what is returned, check to see
// if there are anymore pages to retrieve.
searchMore(result);
} else {
_console.error(getStatusDetails(result.getStatus()));
}
}
5
tried above code still getting null
RecordRef[] recordRefs=new RecordRef[scsf.length];
for(int j=0;j<scsf.length;j++){
RecordRef recordRef=new RecordRef();
recordRef.setInternalId(scsf[j].getSearchValue().getInternalId());
recordRefs[j]=recordRef;
}
SearchMultiSelectField smsf=new SearchMultiSelectField(recordRefs, SearchMultiSelectFieldOperator.anyOf);
TransactionSearchBasic tsc=new TransactionSearchBasic();
tsc.setItem(smsf);
SearchResult searchResult=_port.search(tsc);
System.out.println(searchResult.getStatus().isIsSuccess());
RecordList rl=searchResult.getRecordList();
Record[] rr=rl.getRecord();
for(Record rcd:rr){
if(rcd instanceof SalesOrder){
SalesOrderItemList salesOrderItemList=((SalesOrder) rcd).getItemList();
SalesOrderItem[] items=salesOrderItemList.getItem();
for(SalesOrderItem soi:items){
System.out.println(soi.getItem().getName());
}
}
Check the size and observe it is returning correct number of records or not?
if (searchResult.getStatus().isIsSuccess())
{
RecordList recList = searchResult.getRecordList();
int len = recList.getRecord().length;
CustomRecordType[] crt = new CustomRecordType[len];
for (int i = 0; i < len; i++)
{
crt[i] = (CustomRecordType)recList.getRecord()[i];
_console.writeLn("Record: " + crt[i].getRecordName() + " " + crt[i].getInternalId());
}
}
When performing searches on records, by default only the body fields are returned only. To return field (line item) values for all sublists on a record, you must set the bodyFieldsOnly element to FALSE.
It is recommended that the default settings are used wherever sublist values are not necessary since this significantly improves performance.
Following is the java sample code to set the search preferences......
tried this too,getting records size but can´t get field values.Still facing null pointer exception
Hi Garima gupta,
i have tried your suggestion too,set the body field to false before retrival of field values,but didn´t worked..
This is the last hope AFAIK....
In this example, a SearchPreference object is instantiated and search preferences are set by java code.
NetSuiteBindingStub stub = (NetSuiteBindingStub)aPort;
stub.clearHeaders();
SOAPHeaderElement searchPrefHeader = new
SOAPHeaderElement("urn:messages_2_5.platform.webservices.netsuite.com",
"searchPreferences");
SearchPreferences searchPrefs = new SearchPreferences();
searchPrefs.setPageSize(new Integer(nPageSize));
searchPrefs.setBodyFieldsOnly(isBodyFieldsOnly);
searchPrefHeader.setObjectValue(searchPrefs);
stub.setHeader(searchPrefHeader);
5
Nice point Garima ji!
Hi Garima ji,
Suggest me if any wrong with the following code.
TransactionSearchAdvanced tsa=new TransactionSearchAdvanced();
tsa.setSavedSearchId("825");
NetSuiteBindingStub stub = (NetSuiteBindingStub)_port;
stub.clearHeaders();
SOAPHeaderElement searchPrefHeader = new
SOAPHeaderElement("urn:messages_2_5.platform.webservices.netsuite.com",
"searchPreferences");
SearchPreferences searchPrefs = new SearchPreferences();
String nPageSize="1";
searchPrefs.setPageSize(new Integer(nPageSize));
Boolean isBodyFieldsOnly=false;
searchPrefs.setBodyFieldsOnly(isBodyFieldsOnly);
searchPrefHeader.setObjectValue(searchPrefs);
stub.setHeader(searchPrefHeader);
SearchResult result = _port.search(tsa);
System.out.println("11111111111..."+result.getTotalRecords());
What is the problem in this code? It´s correct.
getting null for size of total records.If i remove the code which you suggested(above post) then getting size of records.
I have described all possible situation completely in first answer.. and i am also not able to find what´s the problem with you.
Thanks Raj for your great help.my problem is not able to get the values for list type fields.anyhow thanks for your help
.@Raj,@Garima