Search code examples
atgatg-dynamo

How write RQLQuery?


I am new to ATG, and I have this question. How can I write my RQLQuery that provide me data, such as this SQL query?

select avg(rating) from rating WHERE album_id = ?;

I'm trying this way:

RqlStatement statement;
    Object rqlparam[] = new Object[1];
    rqlparam[0] = album_Id;
    statement= RqlStatement.parseRqlStatement("album_id= ? 0");
    MutableRepository repository = (MutableRepository) getrMember();
    RepositoryView albumView = repository.getView(ALBUM);

This query returns me an item for a specific album_id, how can I improve my RQL query so that it returns to me the average field value, as SQL query above.


Solution

  • There is no RQL syntax that will allow for the calculation of an average value for items in the query. As such you have two options. You can either execute your current statement:

    album_id= ? 0
    

    And then loop through the resulting RepositoryItem[] and calculate the average yourself (this could be time consuming on large datasets and means you'll have to load all the results into memory, so perhaps not the best solution) or you can implement a SqlPassthroughQuery that you execute.

    Object params[] = new Object[1];
    params[0] = albumId;
    
    Builder builder = (Builder)view.getQueryBuilder();
    String str = "select avg(rating) from rating WHERE album_id = 1 group by album_id";
    
    RepositoryItem[] items =
        view.executeQuery (builder.createSqlPassthroughQuery(str, params));
    

    This will execute the average calculation on the database (something it is quite good at doing) and save you CPU cycles and memory in the application.

    That said, don't make a habit of using SqlPassthroughQuery as means you don't get to use the repository cache as much, which could be detrimental to your application.