Reputation: 191
I am using Grails 2.3.7. I have exposed my controller as REST controller by over riding the restfull controller interface. My client is AngularJS. My CRUD operations are working fine. I have now a requirement to write search API on various objects like search on account name and number or for customer object search on customer email.
What should be an efficient and best way to write such search API? I can write an API for each search criteria but looking for something generic where a search criteria can be posted as JSON and be applied on the corresponding resource object. Is there any such generic way to implement this?
Jay
Upvotes: 3
Views: 1533
Reputation: 182
For Grails 3.0.8+ you can try this grails-restsearch-plugin
It uses default GORM (don't need to use SOLR, ES or other search engines) Adds a REST and search capabilities to the project but you can ignore the REST part and use only the search
Upvotes: 1
Reputation: 49572
I think the problem here is that search is quite a large field.
If you need real search features you should definitely look at a third party search server like solr or elasticsearch and the corresponding Grails plugins. These products are create a separate index out of your data and provide features like faceted search, spelling suggestions for query input, result highlighting and much more (and are highly scalable).
However, since you mentioned that you don't want to use third party libraries you might be looking for something much simpler.
A very basic solution to your problem could be something like this:
class CustomerController extends RestfulController {
...
def search(String property, String value) {
respond Customer.createCriteria().list {
like property, "%$value%"
}
}
}
This creates a Gorm criteria query that queries for Customer
objects with a field that matches a SQL like condition.
Calling this action with a url like
/customer/search?property=lastname&value=foo
would return all Customers with a lastname
that contains foo
.
You can easily make this action more generic by using an addional parameter for the domain class:
def searchWithClass(String className, String property, String value) {
def domainClass = grailsApplication.getDomainClass(className).clazz
respond domainClass.createCriteria().list {
like property, "%$value%"
}
}
Now you can pass the domain class you want to query using the className
parameter:
.../searchWithClass?property=lastname&value=foo&className=foo.bar.Customer
But keep some things in mind when using an approach like this:
like
queries might not be the best (especially if you have very large text fields)Upvotes: 2