public virtual List <SkinnyItem> RunQuery(Query query, bool showAllVersions, Sort sorter, int start, int end, out int totalResults) { Assert.ArgumentNotNull(Index, "Index"); var items = new List <SkinnyItem>(); if (query == null || string.IsNullOrEmpty(query.ToString())) { Log.Debug("SitecoreSearchContrib: Attempt to execute an empty query."); totalResults = 0; return(items); } try { using (var context = new IndexSearchContext(Index)) { Log.Debug(string.Format("SitecoreSearchContrib: Executing query: {0}", query)); SearchHits searchhits; if (sorter != null) { var hits = context.Searcher.Search(query, sorter); searchhits = new SearchHits(hits); } else { searchhits = this.UsePreparedQuery ? context.Search(new PreparedQuery(query)) : context.Search(query); } if (searchhits == null) { totalResults = 0; return(null); } totalResults = searchhits.Length; if (end == 0 || end > searchhits.Length) { end = totalResults; } Log.Debug(string.Format("SitecoreSearchContrib: Total hits: {0}", totalResults)); var resultCollection = searchhits.FetchResults(start, end - start); SearchHelper.GetItemsFromSearchResult(resultCollection, items, showAllVersions); Log.Debug(string.Format("SitecoreSearchContrib: Total results: {0}", resultCollection.Count)); } } catch (Exception exception) { Log.Error("scSearchContrib.Searcher. There was a problem while running a search query. Details: " + exception.Message, this); Log.Error(exception.StackTrace, this); throw; } return(items); }
static void DisplayResults(SearchHits <Page> result) { Console.WriteLine("Displaying page {0} of {1} sorted by relevans:", result.Page, result.NumberOfPages); Console.WriteLine(String.Join(", ", result.Items.Select(x => x.PageNumber))); Console.WriteLine(); Console.WriteLine("Returned {0} out of {1} results in {2} ms.", result.Pagesize, result.TotalHits, result.QueryExecutionTime.TotalMilliseconds); }
public Item[] Search(string index, string[] areas, int maxItems) { List<Item> searchResults = new List<Item>(); var searchIndex = Sitecore.Search.SearchManager.GetIndex(index); using (IndexSearchContext context = searchIndex.CreateSearchContext()) { /***********/ /* First we need to create a BooleanQuery so we can concatenate the different queries */ BooleanQuery completeQuery = new BooleanQuery(); //completeQuery.SetMinimumNumberShouldMatch(2); /* search only in current language */ completeQuery.Add(new TermQuery(new Lucene.Net.Index.Term("_language", Sitecore.Context.Language.Name)), BooleanClause.Occur.MUST); Sort sort = new Sort(new SortField("publish date", true)); Lucene.Net.Search.Searcher searcher = context.Searcher; try { Hits hits = context.Searcher.Search(completeQuery, sort); SearchHits searchHits = new SearchHits(hits); // assuming, no more than every second result is a null-item, that is why the maxItems parameter is multiplied by 2 var results = searchHits.FetchResults(0, maxItems * 2); int count = 0; foreach (SearchResult result in results) { try { Item item = result.GetObject<Item>(); if (item != null) { count++; searchResults.Add(item); } } catch (Exception e) { Log.Error("error while converting lucene search hit in NewsSearcher.cs", e, searchIndex); } if (count >= maxItems) break; } } catch (Exception e) { Log.Error("error while performing a lucene search in NewsSearcher.cs", e, searchIndex); } } return searchResults.ToArray(); }
/// <summary> /// Gets the search result. /// </summary> /// <param name="searchHits">The search hits.</param> /// <returns>Returns collection of search results</returns> public virtual IEnumerable <SearchResult> GetSearchResult(SearchHits searchHits) { List <SearchResult> result = new List <SearchResult>(); foreach (SearchHit hit in searchHits.Slice(0)) { SearchResult sr = new SearchResult(); Item parentItem = null; Item resultItem = null; if (hit.Document.GetField(BuiltinFields.CatalogItemUri) != null) { string catalogUri = this.GetFieldValue(hit.Document, BuiltinFields.CatalogItemUri); if (!string.IsNullOrEmpty(catalogUri)) { parentItem = Database.GetItem(new ItemUri(catalogUri)); resultItem = Database.GetItem(new ItemUri(hit.Url)); if (resultItem != null && parentItem != null) { sr.ResultItem.ItemLink = this.ProductResolver.GetVirtualProductUrl(parentItem, resultItem); } } } else { resultItem = Database.GetItem(new ItemUri(hit.Url)); if (resultItem != null) { ////remove items without visualization from search result. if (resultItem.Visualization != null && resultItem.Visualization.Layout == null) { continue; } sr.ResultItem.ItemLink = LinkManager.GetItemUrl(resultItem); parentItem = resultItem.Parent; } } if (parentItem != null && resultItem != null) { sr.ResultItem.ItemTitle = this.GetItemTitle(resultItem); sr.ResultItem.ItemUri = hit.Url; sr.ParentItem.ItemLink = LinkManager.GetItemUrl(parentItem); sr.ParentItem.ItemTitle = this.GetItemTitle(parentItem); sr.ParentItem.ItemUri = parentItem.Uri.ToString(); } result.Add(sr); } return(result); }
/// <summary> /// Gets the search result. /// </summary> /// <param name="searchHits">The search hits.</param> /// <returns>Returns collection of search results</returns> public virtual IEnumerable<SearchResult> GetSearchResult(SearchHits searchHits) { List<SearchResult> result = new List<SearchResult>(); foreach (SearchHit hit in searchHits.Slice(0)) { SearchResult sr = new SearchResult(); Item parentItem = null; Item resultItem = null; if (hit.Document.GetField(BuiltinFields.CatalogItemUri) != null) { string catalogUri = this.GetFieldValue(hit.Document, BuiltinFields.CatalogItemUri); if (!string.IsNullOrEmpty(catalogUri)) { parentItem = Database.GetItem(new ItemUri(catalogUri)); resultItem = Database.GetItem(new ItemUri(hit.Url)); if (resultItem != null && parentItem != null) { sr.ResultItem.ItemLink = this.ProductResolver.GetVirtualProductUrl(parentItem, resultItem); } } } else { resultItem = Database.GetItem(new ItemUri(hit.Url)); if (resultItem != null) { ////remove items without visualization from search result. if (resultItem.Visualization != null && resultItem.Visualization.Layout == null) { continue; } sr.ResultItem.ItemLink = LinkManager.GetItemUrl(resultItem); parentItem = resultItem.Parent; } } if (parentItem != null && resultItem != null) { sr.ResultItem.ItemTitle = this.GetItemTitle(resultItem); sr.ResultItem.ItemUri = hit.Url; sr.ParentItem.ItemLink = LinkManager.GetItemUrl(parentItem); sr.ParentItem.ItemTitle = this.GetItemTitle(parentItem); sr.ParentItem.ItemUri = parentItem.Uri.ToString(); } result.Add(sr); } return result; }
//NOTE: This required me to bring in the Lucene.Net Reference public long RunWhereSearchManager() { using (var queryTimer = new QueryTimer()) { using (var context = SearchManager.GetIndex("system").CreateSearchContext()) { TermQuery ftQuery = new TermQuery(new Term("_templatename", "sample item")); SearchHits results = context.Search(ftQuery); } return(queryTimer.StopWatch.ElapsedTicks / 1000); } }
//NOTE: This required me to bring in the Lucene.Net Reference public long RunWhereSearchManager5() { using (var queryTimer = new QueryTimer()) { using (var context = SearchManager.GetIndex("system").CreateSearchContext()) { var id1 = IdHelper.NormalizeGuid("{16156647-DE5D-4E6A-A6AE-5B8D4A3A40BE}"); TermQuery ftQuery = new TermQuery(new Term("_path", id1)); SearchHits results = context.Search(ftQuery); } return(queryTimer.StopWatch.ElapsedTicks / 1000); } }
//NOTE: This required me to bring in the Lucene.Net Reference public long RunWhereSearchManager6() { using (var queryTimer = new QueryTimer()) { using (var context = SearchManager.GetIndex("system").CreateSearchContext()) { var id1 = IdHelper.NormalizeGuid("{16156647-DE5D-4E6A-A6AE-5B8D4A3A40BE}"); TermRangeQuery ftQuery = new TermRangeQuery("__updated", "20090101", "20130505", true, true); SearchHits results = context.Search(ftQuery); } return(queryTimer.StopWatch.ElapsedTicks / 1000); } }
//NOTE: This required me to bring in the Lucene.Net Reference public long RunWhereSearchManager3() { using (var queryTimer = new QueryTimer()) { using (var context = SearchManager.GetIndex("system").CreateSearchContext()) { var id1 = IdHelper.NormalizeGuid(Sitecore.ItemIDs.RootID); TermQuery ftQuery = new TermQuery(new Term("_parent", id1)); SearchHits results = context.Search(ftQuery); } return(queryTimer.StopWatch.ElapsedTicks / 1000); } }
/// <summary> /// Runs the query. /// </summary> /// <param name="query">The query.</param> /// <param name="pageSize">Size of the page.</param> /// <param name="pageNumber">The page number.</param> /// <param name="sortField">The sort field.</param> /// <param name="sortDirection">The sort direction.</param> /// <returns>The key value pair of the running query.</returns> public virtual KeyValuePair <int, List <SitecoreItem> > RunQuery( Query query, int pageSize, int pageNumber, string sortField, string sortDirection) { var items = new List <SitecoreItem>(); if (Config.EnableBucketDebug || Constants.EnableTemporaryBucketDebug) { Log.Info("Bucket Debug Query: " + query, this); } if (Config.SolrEnabled == "true") { GetValue(query, items); return(new KeyValuePair <int, List <SitecoreItem> >(items.Count, items)); } if (Index is Index) { (Index as Index).Analyzer = new StandardAnalyzer(Consts.StopWords); } int hitCount; using (var context = new SortableIndexSearchContext(Index)) { BooleanQuery.SetMaxClauseCount(Config.LuceneMaxClauseCount); bool sortingDir = sortDirection != "asc"; SearchHits searchHits = string.IsNullOrWhiteSpace(sortField) ? context.Search(query) : context.Search(query, new Sort(sortField, sortingDir)); if (searchHits.IsNull()) { return(new KeyValuePair <int, List <SitecoreItem> >()); } hitCount = searchHits.Length; if (pageSize == 0 || pageNumber < 1) { pageSize = searchHits.Length; pageNumber = 1; } SearchResultCollection resultCollection = searchHits.FetchResults((pageNumber - 1) * pageSize, pageSize); SearchHelper.GetItemsFromSearchResult(resultCollection, items); } return(new KeyValuePair <int, List <SitecoreItem> >(hitCount, items)); }
public virtual List <SkinnyItem> RunQuery(Query query, bool showAllVersions, string sortField, bool reverse, int start, int end, out int totalResults) { Assert.ArgumentNotNull(Index, "Demo"); var items = new List <SkinnyItem>(); try { using (var context = new IndexSearchContext(Index)) { SearchHits searchhits; if (!sortField.IsNullOrEmpty()) { // type hardcoded to 3 - means sorting as string var sort = new Sort(new SortField(sortField, 3, reverse)); var hits = context.Searcher.Search(query, sort); searchhits = new SearchHits(hits); } else { searchhits = context.Search(query); } if (searchhits == null) { totalResults = 0; return(null); } totalResults = searchhits.Length; if (end == 0 || end > searchhits.Length) { end = totalResults; } var resultCollection = searchhits.FetchResults(start, end); SearchHelper.GetItemsFromSearchResult(resultCollection, items, showAllVersions); } } catch (Exception exception) { Log.Error("scSearchContrib.Searcher. There was a problem while running a search query. Details: " + exception.Message, this); Log.Error(exception.StackTrace, this); throw; } return(items); }
/// <summary> /// Searches the specified query. /// </summary> /// <param name="query">The query.</param> /// <param name="database">The database.</param> /// <returns>Returns collection of items</returns> public override IEnumerable <Item> Search(Query query, Database database) { Assert.ArgumentNotNull(query, "query"); Assert.ArgumentNotNull(database, "database"); string indexName = string.IsNullOrEmpty(this.IndexName) ? "products" : this.IndexName; IEnumerable <Item> items; LuceneQueryBuilder builder = new LuceneQueryBuilder(query, this.Database); BooleanQuery luceneQuery = builder.BuildResultQuery(); using (IndexSearchContext context = SearchManager.GetIndex(indexName).CreateSearchContext()) { this.AddDecorations(luceneQuery, database.Name); PreparedQuery pq = new PreparedQuery(luceneQuery); ////Sitecore Query parser does not allow to use IDs in field values. SearchHits hits = context.Search(pq, int.MaxValue); items = this.GetSearchResultItems(hits); } return(items); }
private TextSegment Replace(string replaceTerm, int startLookingFrom, bool selectSearch) { // Compute the selection offset BEFORE performing the replacement var correctionOffset = replaceTerm.Trim().Length - view.Editor.TextArea.Selection.Length; view.Editor.TextArea.Selection.ReplaceSelectionWithText(replaceTerm.Trim()); var foundHit = (SearchHits as TextSegmentCollection <TextSegment>).FindFirstSegmentWithStartAfter(startLookingFrom); foundHit.ExecuteSafely(hit => { // special case: don't select text when CTRL+F pressed with an old, existing search, just highlight if (selectSearch) { view.Editor.Select(hit.StartOffset + correctionOffset, hit.Length); view.Editor.ScrollToLine(view.Editor.Document.GetLineByOffset(view.Editor.SelectionStart).LineNumber); } lastCaretPosition = view.Editor.CaretOffset; CurrentHitIndex = SearchHits.Select((v, i) => new { hit = v, index = i }).First(arg => arg.hit.Equals(foundHit)).index + 1; }); return(foundHit); }
public void DoSearch(SearchType searchType, bool selectSearch) { if (view == null) { return; } if (!view.TextView.VisualLinesValid) { return; } ClearSearchHits(); if (searchSettings == null) { return; } if (string.IsNullOrEmpty(searchSettings.SearchTerm)) { return; } var searchTerm = searchSettings.SearchTerm; if (!searchSettings.Regex) { searchTerm = Regex.Escape(searchTerm); } if (searchSettings.WholeWord) { searchTerm = @"\b" + searchTerm + @"\b"; } if (!searchSettings.CaseSensitive) { searchTerm = @"(?i)" + searchTerm; } foreach (DocumentLine currentDocLine in view.Document.Lines) { VisualLine currentLine = view.TextView.GetOrConstructVisualLine(currentDocLine); string originalText = view.Document.GetText(currentLine.FirstDocumentLine.Offset, currentLine.LastDocumentLine.EndOffset - currentLine.FirstDocumentLine.Offset); try { foreach (Match match in Regex.Matches(originalText, searchTerm)) { var textSegment = new TextSegment { StartOffset = currentLine.FirstDocumentLine.Offset + match.Index, Length = match.Length }; searchRenderer.SearchHitsSegments.Add(textSegment); } } catch (ArgumentException) {} // catch malformed regex } TextSegment newFoundHit = null; var startLookingFrom = view.Editor.CaretOffset; // consider the already selected text when searching, skip it on SearchType.Next if (!view.Editor.TextArea.Selection.IsEmpty && searchType != SearchType.Next) { startLookingFrom = view.Editor.SelectionStart; } switch (searchType) { case SearchType.Normal: case SearchType.Next: newFoundHit = (from hit in SearchHits let hitDistance = hit.StartOffset - startLookingFrom where hitDistance >= 0 orderby hitDistance select hit) .FirstOrDefault() ?? SearchHits.FirstOrDefault(); break; case SearchType.Prev: newFoundHit = (from hit in SearchHits let hitDistance = hit.StartOffset - startLookingFrom where hitDistance < 0 orderby hitDistance descending select hit) .FirstOrDefault() ?? SearchHits.Reverse().FirstOrDefault(); break; } // logic for explicit searches if (searchType != SearchType.NoSelect) { newFoundHit.ExecuteSafely(hit => { // special case: don't select text when CTRL+F pressed with an old, existing search, just highlight if (selectSearch) { view.Editor.Select(hit.StartOffset, hit.Length); view.Editor.ScrollToLine(view.Editor.Document.GetLineByOffset(view.Editor.SelectionStart).LineNumber); } lastCaretPosition = view.Editor.CaretOffset; CurrentHitIndex = SearchHits.Select((v, i) => new { hit = v, index = i }).First(arg => arg.hit.Equals(newFoundHit)).index + 1; }); } NumberOfHits = searchRenderer.SearchHitsSegments.Count; // don't show index of a match if we're searching without a search bar, if there are no matches, or if we're in a NoSelect search and there isn't an already selected old match in the editor var selectedText = new TextSegment { StartOffset = view.Editor.SelectionStart, Length = view.Editor.SelectionLength }; if (!searchSettings.SearchingWithBar || !searchRenderer.SearchHitsSegments.Any() || (!selectSearch && newFoundHit != null && !newFoundHit.EqualsByValue(selectedText))) { CurrentHitIndex = 0; } // don't highlight matches when searching without the search bar if (!searchSettings.SearchingWithBar) { ClearSearchHits(); } }
static void Main(string[] args) { while (true) { Console.Write("Enter a querystring:"); var queryString = Console.ReadLine(); var proxy = new KDListManagerClient(); try { proxy.Open(); SearchHits <Page> result = proxy.Search(new PageQueryParameter(queryString, _fileId)); DisplayResults(result); } catch (Exception) { Console.WriteLine("Cannot process..."); } finally { if (proxy.State == CommunicationState.Faulted) { proxy.Abort(); } else { proxy.Close(); } } Console.WriteLine(); } //return; //Lucene.Net.Util.Version version = Lucene.Net.Util.Version.LUCENE_29; //Directory dir = FSDirectory.Open(new DirectoryInfo(@"C:\HK Data\FullIndex\FileIndex")); //Analyzer analyzer = new StandardAnalyzer(version); //var parser = new MultiFieldQueryParser(version, new[] { "NumberOfPages" }, analyzer); //Query q = parser.Parse("[100000 TO 9999999999999999]"); //var searcher = new IndexSearcher(dir, true); //TopDocs hits = searcher.Search(q, null, 10, new Sort(new SortField("NumberOfPages", true))); //Console.WriteLine("Found {0} document(s) that matched query '{1}':", hits.TotalHits, q); //foreach (ScoreDoc match in hits.ScoreDocs) //{ // Document doc = searcher.Doc(match.Doc); // Console.WriteLine("Matched id = {0}, NumberOfPages = {1}", doc.Get("Id"), doc.Get("NumberOfPages")); // //Console.WriteLine(Explain(searcher, q, match)); //} //searcher.Close(); //dir.Close(); }
public virtual List<SkinnyItem> RunQuery(Query query, bool showAllVersions, string sortField, bool reverse, int start, int end, out int totalResults) { Assert.ArgumentNotNull(Index, "Demo"); var items = new List<SkinnyItem>(); try { using (var context = new IndexSearchContext(Index)) { SearchHits searchhits; if (!sortField.IsNullOrEmpty()) { // type hardcoded to 3 - means sorting as string var sort = new Sort(new SortField(sortField, 3, reverse)); var hits = context.Searcher.Search(query, sort); searchhits = new SearchHits(hits); } else { searchhits = context.Search(query); } if (searchhits == null) { totalResults = 0; return null; } totalResults = searchhits.Length; if (end == 0 || end > searchhits.Length) end = totalResults; var resultCollection = searchhits.FetchResults(start, end); SearchHelper.GetItemsFromSearchResult(resultCollection, items, showAllVersions); } } catch (Exception exception) { Log.Error("scSearchContrib.Searcher. There was a problem while running a search query. Details: " + exception.Message, this); Log.Error(exception.StackTrace, this); throw; } return items; }
/// <summary> /// Gets the search result items. /// </summary> /// <param name="hits">The search hits.</param> /// <returns>Returns a list of items</returns> protected virtual IEnumerable<Item> GetSearchResultItems(SearchHits hits) { return hits.FetchResults(0, 0).Select<SearchResult, Item>(res => res.GetObject<Item>()); }
public virtual List<SkinnyItem> RunQuery(Query query, bool showAllVersions, Sort sorter, int start, int end, out int totalResults) { Assert.ArgumentNotNull(Index, "Index"); var items = new List<SkinnyItem>(); if (query == null || string.IsNullOrEmpty(query.ToString())) { Log.Debug("SitecoreSearchContrib: Attempt to execute an empty query."); totalResults = 0; return items; } try { using (var context = new IndexSearchContext(Index)) { Log.Debug(string.Format("SitecoreSearchContrib: Executing query: {0}", query)); SearchHits searchhits; if (sorter != null) { var hits = context.Searcher.Search(query, sorter); searchhits = new SearchHits(hits); } else { searchhits = this.UsePreparedQuery ? context.Search(new PreparedQuery(query)) : context.Search(query); } if (searchhits == null) { totalResults = 0; return null; } totalResults = searchhits.Length; if (end == 0 || end > searchhits.Length) { end = totalResults; } Log.Debug(string.Format("SitecoreSearchContrib: Total hits: {0}", totalResults)); var resultCollection = searchhits.FetchResults(start, end - start); SearchHelper.GetItemsFromSearchResult(resultCollection, items, showAllVersions); Log.Debug(string.Format("SitecoreSearchContrib: Total results: {0}", resultCollection.Count)); } } catch (Exception exception) { Log.Error("scSearchContrib.Searcher. There was a problem while running a search query. Details: " + exception.Message, this); Log.Error(exception.StackTrace, this); throw; } return items; }
/// <summary> /// Gets the search result items. /// </summary> /// <param name="hits">The search hits.</param> /// <returns>Returns a list of items</returns> protected virtual IEnumerable <Item> GetSearchResultItems(SearchHits hits) { return(hits.FetchResults(0, 0).Select <SearchResult, Item>(res => res.GetObject <Item>())); }