Environment
- Umbraco version 7.6.3 assembly: 1.0.6361.21154
- VS2015
Reference
https://techvalut.blogspot.hk/2017/09/how-to-include-custom-properties-in.html
http://www.codeshare.co.uk/videos/how-to-build-a-site-with-umbraco-part-12-advanced-search/
Partial Code for search condition of !(A ==1) & ( (B==SearchTerm) || (C==SearchTerm) )
ISearchCriteria searchCriteria = ExamineManager.Instance.CreateSearchCriteria(BooleanOperation.And);
IBooleanOperation queryNodes = null;
queryNodes = searchCriteria.GroupedOr(new string[] { "B", "C" }, "searchTerm");
queryNodes = queryNodes.Not().GroupedOr(new string[] {"A"}, "1");
ExamineManager.Instance.Search(queryNodes.Compile());
Search View
<section class="container">
<div class="row">
<div class="col-xs-12">
<p></p>
@{ Html.RenderAction("RenderSearchForm", "Search", new { docTypeAliases = "blogPost,videoPost,home",
fieldPropertyAliases = "title,subTitle,articleIntro,body,intro,nodeName,metaName,metaKeyWords,metaDescription,contentGrid",
inclusionExclusionFieldPropertyAliases = "excludeFromSearch:1",
pageSize = 10,
pagingGroupSize = 3,
isIncludePDFContent = true}); }
</div>
</div>
</section>
Controller
[HttpGet]
public ActionResult RenderSearchForm(string query, string docTypeAliases, string fieldPropertyAliases, string inclusionExclusionFieldPropertyAliases, int pageSize, int pagingGroupSize, bool isIncludePDFContent)
{
SearchView model = _searchHelper.GetSearchFormItemsModel(query,
docTypeAliases,
fieldPropertyAliases,
inclusionExclusionFieldPropertyAliases,
pageSize,
pagingGroupSize,
isIncludePDFContent,
searchtitleDictionaryAlias: "Title",
searchPlaceHolderDictionaryAlias: "PlaceHolder",
searchSendButtonDictionaryAlias: "Send Button");
return PartialView(GetViewPath("_SearchForm"), model);
}
[HttpPost]
public ActionResult SubmitSearchForm(SearchView model)
{
if (ModelState.IsValid)
{
if (!string.IsNullOrEmpty(model.SearchTerm))
// && !string.IsNullOrEmpty(model.Category))
{
model.SearchTerm = model.SearchTerm;
model.SearchGroups = _searchHelper.GetSearchGroupsItemsModel(model);
model.SearchExcludeGroups = _searchHelper.GetSearchExcludeGroupsItemsModel(model);
model.SearchResults = _searchHelper.GetSearchResults(model, Request.Form.AllKeys);
}
return RenderSearchResults(model.SearchResults);
}
return null;
}
Partial View
@using Intranet.Library.Models
@model SearchView
@*@using (Html.BeginUmbracoForm("SubmitSearchForm", "Search", FormMethod.Post))*@
@using (Ajax.BeginForm("SubmitSearchForm", "Search", null, new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "search-results"
}))
{
@Html.HiddenFor(m => m.DocTypeAliases)
@Html.HiddenFor(m => m.FieldPropertyAliases)
@Html.HiddenFor(m => m.InclusionExclusionFieldPropertyAliases)
@Html.HiddenFor(m => m.PageSize)
@Html.HiddenFor(m => m.PagingGroupSize)
@Html.HiddenFor(m => m.IsIncludePDFContent)
@Model.Title
@Html.TextBoxFor(m => m.SearchTerm, new { placeholder = Model.SearchPlaceHolder, @class = "form-control" })
@*
@{ Html.RenderAction("RenderCategoryList", "Search");}
*@
@{ Html.RenderAction("RenderSearchResults", "Search", new { Model = Model.SearchResults });}
}
Helper Class
public SearchResults GetSearchResults(SearchView searchModel, string[] allKeys)
{
SearchResults resultsModel = new SearchResults();
resultsModel.SearchTerm = searchModel.SearchTerm;
resultsModel.PageNumber = GetPageNumber(allKeys);
IOrderedEnumerable<SearchResult> allResults = SearchUsingExamine(searchModel.DocTypeAliases.Split(','), searchModel.SearchGroups, searchModel.SearchExcludeGroups, searchModel.SearchTerm, searchModel.IsIncludePDFContent);
resultsModel.TotalItemCount = allResults.Count();
resultsModel.Results = GetResultsForThisPage(allResults, resultsModel.PageNumber, searchModel.PageSize);
resultsModel.PageCount = Convert.ToInt32(Math.Ceiling((decimal)resultsModel.TotalItemCount / (decimal)searchModel.PageSize));
resultsModel.PagingBounds = GetPagingBounds(resultsModel.PageCount, resultsModel.PageNumber, searchModel.PagingGroupSize);
return resultsModel;
}
private IEnumerable<IPublishedContent> GetResultsForThisPage(IOrderedEnumerable<SearchResult> allResults, int pageNumber, int pageSize)
{
return allResults.Skip((pageNumber - 1) * pageSize).Take(pageSize).Select(x => GetPublishedContent(x.Id, x.Fields["__IndexType"]));
}
private IPublishedContent GetPublishedContent(int id, string type)
{
switch (type)
{
case "media":
return _uHelper.TypedMedia(id);
case "content":
default:
return _uHelper.TypedContent(id);
}
}
private ISearchResults SearchWebContentUsingExamine(string[] documentTypes, List<SearchGroup> searchGroups, List<SearchGroup> searchExcludeGroups)
{
ISearchCriteria searchCriteria = ExamineManager.Instance.CreateSearchCriteria(BooleanOperation.And);
IBooleanOperation queryNodes = null;
queryNodes = searchCriteria.GroupedNot(new string[] { "dummy" }, "1");
//exclude field property alias
if (searchExcludeGroups != null && searchExcludeGroups.Any())
{
foreach (SearchGroup searchGroup in searchExcludeGroups)
{
queryNodes = queryNodes.Not().GroupedOr(searchGroup.FieldsToSearchIn, searchGroup.SearchTerms);
}
}
if (documentTypes != null && documentTypes.Length > 0)
{
//only get results for documents of a certain type
queryNodes = queryNodes.And().GroupedOr(new string[] { _docTypeAliasFieldName }, documentTypes);
}
if (searchGroups != null && searchGroups.Any())
{
//in each search group it looks for a match where the specified fields contain any of the specified search terms
//usually would only have 1 search group, unless you want to filter out further, i.e. using categories as well as search terms
foreach (SearchGroup searchGroup in searchGroups)
{
queryNodes = queryNodes.And().GroupedOr(searchGroup.FieldsToSearchIn, searchGroup.SearchTerms);
}
}
//return all results of the search
return ExamineManager.Instance.Search(queryNodes.Compile());
}
private ISearchResults SearchPdfContentUsingExamine(List<SearchGroup> searchExcludeGroups, string searchTerm, bool isIncludePDFContent)
{
if (isIncludePDFContent)
{
var searcher = ExamineManager.Instance.SearchProviderCollection["PDFSearcher"];
if (searcher == null)
return null;
var searchCriteria = searcher.CreateSearchCriteria(BooleanOperation.And);
IBooleanOperation queryNodes = null;
queryNodes = searchCriteria.GroupedOr(new string[] { "FileTextContent" }, new string[] { searchTerm });
//exclude field property alias
if (searchExcludeGroups != null && searchExcludeGroups.Any())
{
foreach (SearchGroup searchGroup in searchExcludeGroups)
{
queryNodes = queryNodes.Not().GroupedOr(searchGroup.FieldsToSearchIn, searchGroup.SearchTerms);
}
}
return searcher.Search(queryNodes.Compile());
}
return null;
}
public IOrderedEnumerable<SearchResult> SearchUsingExamine(string[] documentTypes, List<SearchGroup> searchGroups, List<SearchGroup> searchExcludeGroups, string searchTerm, bool isIncludePDFContent)
{
ISearchResults webPageContentSearchResults = SearchWebContentUsingExamine(documentTypes, searchGroups, searchExcludeGroups);
ISearchResults pdfContentSearchResults = SearchPdfContentUsingExamine(searchExcludeGroups, searchTerm, isIncludePDFContent);
IOrderedEnumerable<SearchResult> orderedSearchResultsAll = pdfContentSearchResults != null ? webPageContentSearchResults.Concat(pdfContentSearchResults).OrderByDescending(n => n.Score) : webPageContentSearchResults.OrderByDescending(n => n.Score);
return orderedSearchResultsAll;
}
public List<SearchGroup> GetSearchGroupsItemsModel(SearchView model)
{
List<SearchGroup> searchGroups = null;
if (!string.IsNullOrEmpty(model.FieldPropertyAliases))
{
searchGroups = new List<SearchGroup>();
searchGroups.Add(new SearchGroup(model.FieldPropertyAliases.Split(','), new string[] { model.SearchTerm }));
}
if (!string.IsNullOrEmpty(model.Category))
{
searchGroups = searchGroups ?? new List<SearchGroup>();
searchGroups.Add(new SearchGroup(new string[] { _categoryDocTypeAlias }, new string[] { model.Category }));
}
return searchGroups;
}
public List<SearchGroup> GetSearchExcludeGroupsItemsModel(SearchView model)
{
List<SearchGroup> searchGroups = null;
if (!string.IsNullOrEmpty(model.InclusionExclusionFieldPropertyAliases))
{
Dictionary<string, string> dict = model.InclusionExclusionFieldPropertyAliases.Split(',').Select(item => item.Split(':')).ToDictionary(s => s[0], s => s[1]);
if (dict != null)
{
foreach(var item in dict)
{
searchGroups = searchGroups ?? new List<SearchGroup>();
searchGroups.Add(new SearchGroup(new string[] { item.Key }, new string[] { item.Value }));
}
}
}
return searchGroups;
}
public int GetPageNumber(string[] formKeys)
{
int pageNumber = 1;
const string NAME_PREFIX = "page";
const char NAME_SEPARATOR = '-';
if (formKeys != null)
{
string pagingButtonName = formKeys.Where(x => x.Length > NAME_PREFIX.Length && x.Substring(0, NAME_PREFIX.Length).ToLower() == NAME_PREFIX).FirstOrDefault();
if (!string.IsNullOrEmpty(pagingButtonName))
{
string[] pagingButtonNameParts = pagingButtonName.Split(NAME_SEPARATOR);
if (pagingButtonNameParts.Length > 1)
{
if (!int.TryParse(pagingButtonNameParts[1], out pageNumber))
{
//pageNumber already set in tryparse
}
}
}
}
return pageNumber;
}
public PagingBounds GetPagingBounds(int pageCount, int pageNumber, int groupSize)
{
int middlePageNumber = (int)(Math.Ceiling((decimal)groupSize / 2));
int pagesBeforeMiddle = groupSize - (int)middlePageNumber;
int pagesAfterMiddle = groupSize - (pagesBeforeMiddle + 1);
int startPage = 1;
if (pageNumber >= middlePageNumber)
{
startPage = pageNumber - pagesBeforeMiddle;
}
else
{
pagesAfterMiddle = groupSize - pageNumber;
}
int endPage = pageCount;
if (pageCount >= (pageNumber + pagesAfterMiddle))
{
endPage = (pageNumber + pagesAfterMiddle);
}
bool showFirstButton = startPage > 1;
bool showLastButton = endPage < pageCount;
return new PagingBounds(startPage, endPage, showFirstButton, showLastButton);
}
public SearchView GetSearchFormItemsModel(string query,
string docTypeAliases,
string fieldPropertyAliases,
string inclusionExclusionFieldPropertyAliases,
int pageSize,
int pagingGroupSize,
bool includePDFContent = false)
{
SearchView model = new SearchView();
if (!string.IsNullOrEmpty(query))
{
model.SearchTerm = query;
model.DocTypeAliases = docTypeAliases;
model.FieldPropertyAliases = fieldPropertyAliases;
model.InclusionExclusionFieldPropertyAliases = inclusionExclusionFieldPropertyAliases;
model.PageSize = pageSize;
model.PagingGroupSize = pagingGroupSize;
model.IsIncludePDFContent = includePDFContent;
model.SearchGroups = GetSearchGroupsItemsModel(model);
model.SearchResults = GetSearchResults(model, _httpContext.Request.Form.AllKeys);
}
return model;
}
沒有留言:
張貼留言