Querying in views with IPublishedContentQuery in Umbraco
The IPublishedContentQuery interface contains different query methods for accessing strongly typed content in services etc.
How to inject IPublishedContentQuery
In order to inject the IPublishedContentQuery into your services, you must add a using statement for Umbraco.Cms.Core and inject the service using the constructor.
Now you can access the IPublishedContentQuery through _publishedContentQuery
Examples
.Search(string term)
By default, IPublishedContentQuery will search on Umbraco's 'External' search index for any published content matching the provided search term.
publicIEnumerable<PublishedSearchResult> Search(string searchTerm){foreach (var result in_publishedContentQuery.Search(searchTerm)) {yieldreturn result; }}
.Search(string term, int skip, int take, out long totalRecords)
Specifying the number of records 'to skip' and the number of records 'to take' improves performance with many matching search results. This approach is beneficial when there is a requirement to implement paging.
publicIEnumerable<PublishedSearchResult> Search(string searchTerm,int skip =5,int take =10){foreach (var result in_publishedContentQuery.Search(searchTerm, skip, take,outlong totalRecords)) {yieldreturn result; }}
.Search(IQueryExecutor queryExecutor)
For more complex searching you can construct an Examine QueryExecutor. In the example the search will execute against content of type "blogPost" only. Further information on using Examine
usingSystem;usingSystem.Collections.Generic;usingExamine;usingUmbraco.Cms.Core;usingUmbraco.Cms.Core.Models.PublishedContent;usingUmbraco.Cms.Infrastructure.Examine;usingUmbraco.Extensions;namespaceUmbraco.Docs.Samples.Web.Services;publicclassSearchService{privatereadonlyIPublishedContentQuery _publishedContentQuery;privatereadonlyIExamineManager _examineManager;publicSearchService(IPublishedContentQuery publishedContentQuery,IExamineManager examineManager) { _publishedContentQuery = publishedContentQuery; _examineManager = examineManager; }publicIEnumerable<PublishedSearchResult> Search(string searchTerm) {if (!_examineManager.TryGetIndex(Constants.UmbracoIndexes.ExternalIndexName,outIIndex index)) {thrownewInvalidOperationException($"No index found by name{Constants.UmbracoIndexes.ExternalIndexName}"); }var query =index.Searcher.CreateQuery(IndexTypes.Content);var queryExecutor =query.NodeTypeAlias("blogPost").And().ManagedQuery(searchTerm);foreach (var result in_publishedContentQuery.Search(queryExecutor)) {yieldreturn result; } }}