Skip to content

Instantly share code, notes, and snippets.

@mskutta
Created November 2, 2016 18:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mskutta/95321f7369a375886a594941113bf4c3 to your computer and use it in GitHub Desktop.
Save mskutta/95321f7369a375886a594941113bf4c3 to your computer and use it in GitHub Desktop.
Sorting Sitecore Items by Popularity using xDB
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