Friday, November 9, 2012

Nested OR Criteria on the CD

A few months ago during an onsite assignment, I was asked by a customer to advise them about how to get all the latest updated content on their wrbsite. 

I had what to me looked like a simple requirement: “Show all the latest updated content on the site”. There could be up to 10 content types. I was working on a query object to retrieve all the components of type X,Y,Z… sorted by latest modified date.

Everything worked fine until I added a fourth ItemSchemaCriteria, I wondered if I was building the query in the wrong way (less efficient), if I removed the lines I highlighted below then everything worked fine. Here is the code I used:

            Criteria onlyComponents = new ItemTypeCriteria(16);

            Criteria productSpecs = new ItemSchemaCriteria(2448);
            Criteria events = new ItemSchemaCriteria(6258);
            Criteria madeUp1 = new ItemSchemaCriteria(1234);
            Criteria madeUp2 = new ItemSchemaCriteria(1235);

            Criteria cOr1 = new OrCriteria(productSpecs, events);
            Criteria cOr2 = new OrCriteria(cOr1, madeUp1);
            Criteria cOr3 = new OrCriteria(cOr2, madeUp2);

            Criteria criteria = new AndCriteria(onlyComponents, cOr3);

            Query latestUpdatesQuery = new Query(criteria);

Then a colleague (Jeremy Grand-Scrutton) told me that maybe the way I was creating the several OR criteria wasn't the most efficient way to use the API, and suggested to create an OR criteria array instead. 

       Criteria onlyComponents = new ItemTypeCriteria(16);

            Criteria productSpecs = new ItemSchemaCriteria(2448);
            Criteria events = new ItemSchemaCriteria(6258);
            Criteria madeUp1 = new ItemSchemaCriteria(1234);
            Criteria madeUp2 = new ItemSchemaCriteria(1235);

            Criteria[] itemSchemas = { productSpecs, events, madeUp1, madeUp2 };
            Criteria orCrit = new OrCriteria(itemSchemas);

            Criteria criteria = new AndCriteria(onlyComponents, orCrit);

            Query latestUpdatesQuery = new Query(criteria);

I was very happy when I actually confirmed that it worked out with no issues. In fact, I tested the same logic with up to 30 schemas and surprisingly it still was lighting fast!

No comments:

Post a Comment