Created
November 2, 2016 18:26
-
-
Save mskutta/95321f7369a375886a594941113bf4c3 to your computer and use it in GitHub Desktop.
Sorting Sitecore Items by Popularity using xDB
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static List<Item> GetMostViewed(int count, int daysToInclude, List<Guid> templateIDs, List<Guid> mostViewedExcludeGuids) | |
{ | |
var sqlServerDataApi = new SqlServerDataApi(Sitecore.Configuration.Settings.GetConnectionString("reporting")); | |
// Base Query | |
var query = @"SELECT TOP " + count.ToString() + @" | |
A.ItemId, | |
A.DailyCount, | |
A.LastViewDate | |
FROM | |
( | |
SELECT ItemId, | |
SUM([Count]) AS DailyCount, | |
Max(Date) AS LastViewDate | |
FROM Fact_Views | |
WHERE ViewDate >= DATEADD(DAY, -" + daysToInclude.ToString() + @", GETDATE()) "; | |
// Restrict To Search Templates | |
if (templateIDs != null && templateIDs.Any()) | |
{ | |
query += @"AND TemplateId IN (" + string.Join(",", templateIDs.Select(x => string.Format("'{0}'", x.ToString()))) + @") "; | |
} | |
// Exclude Specific ItemIDs | |
if (mostViewedExcludeGuids != null && mostViewedExcludeGuids.Any()) | |
{ | |
query += @"AND ItemId NOT IN (" + string.Join(",", mostViewedExcludeGuids.Select(x => string.Format("'{0}'", x.ToString()))) + @") "; | |
} | |
// Group And Sort | |
query += @"GROUP BY ItemId | |
) AS A | |
ORDER BY A.DailyCount DESC, | |
A.LastViewDate DESC"; | |
var result = new List<Item>(); | |
var reader = sqlServerDataApi.CreateReader(query); | |
while (reader.Read()) | |
{ | |
var itemID = reader.InnerReader.GetGuid(0); | |
var scItem = Sitecore.Context.Database.GetItem(new ID(itemID)); | |
if (scItem != null) | |
{ | |
result.Add(scItem); | |
} | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment