LuceneSearchEngine.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. using MediaBrowser.Controller;
  2. using MediaBrowser.Controller.Entities;
  3. using MediaBrowser.Controller.Entities.Audio;
  4. using MediaBrowser.Controller.Library;
  5. using MediaBrowser.Model.Logging;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Linq;
  9. using System.Threading.Tasks;
  10. namespace MediaBrowser.Server.Implementations.Library
  11. {
  12. /// <summary>
  13. /// Class LuceneSearchEngine
  14. /// http://www.codeproject.com/Articles/320219/Lucene-Net-ultra-fast-search-for-MVC-or-WebForms
  15. /// </summary>
  16. public class LuceneSearchEngine : ILibrarySearchEngine, IDisposable
  17. {
  18. private readonly ILibraryManager _libraryManager;
  19. private readonly ILogger _logger;
  20. public LuceneSearchEngine(IServerApplicationPaths serverPaths, ILogManager logManager, ILibraryManager libraryManager)
  21. {
  22. _libraryManager = libraryManager;
  23. _logger = logManager.GetLogger("Lucene");
  24. }
  25. /// <summary>
  26. /// Searches items and returns them in order of relevance.
  27. /// </summary>
  28. /// <param name="items">The items.</param>
  29. /// <param name="searchTerm">The search term.</param>
  30. /// <returns>IEnumerable{BaseItem}.</returns>
  31. /// <exception cref="System.ArgumentNullException">searchTerm</exception>
  32. public IEnumerable<BaseItem> Search(IEnumerable<BaseItem> items, string searchTerm)
  33. {
  34. return items;
  35. }
  36. public void Dispose()
  37. {
  38. //BaseItem.LibraryManager.LibraryChanged -= LibraryChanged;
  39. //LuceneSearch.CloseAll();
  40. }
  41. /// <summary>
  42. /// Gets the search hints.
  43. /// </summary>
  44. /// <param name="inputItems">The input items.</param>
  45. /// <param name="searchTerm">The search term.</param>
  46. /// <returns>IEnumerable{SearchHintResult}.</returns>
  47. /// <exception cref="System.ArgumentNullException">searchTerm</exception>
  48. public Task<IEnumerable<SearchHintInfo>> GetSearchHints(IEnumerable<BaseItem> inputItems, string searchTerm)
  49. {
  50. if (string.IsNullOrEmpty(searchTerm))
  51. {
  52. throw new ArgumentNullException("searchTerm");
  53. }
  54. var terms = GetWords(searchTerm);
  55. var hints = new List<Tuple<BaseItem, string, int>>();
  56. var items = inputItems.Where(i => !(i is MusicArtist)).ToList();
  57. // Add search hints based on item name
  58. hints.AddRange(items.Where(i => !string.IsNullOrEmpty(i.Name)).Select(item =>
  59. {
  60. var index = GetIndex(item.Name, searchTerm, terms);
  61. return new Tuple<BaseItem, string, int>(item, index.Item1, index.Item2);
  62. }));
  63. // Find artists
  64. var artists = items.OfType<Audio>()
  65. .SelectMany(i =>
  66. {
  67. var list = new List<string>();
  68. if (!string.IsNullOrEmpty(i.AlbumArtist))
  69. {
  70. list.Add(i.AlbumArtist);
  71. }
  72. list.AddRange(i.Artists);
  73. return list;
  74. })
  75. .Where(i => !string.IsNullOrEmpty(i))
  76. .Distinct(StringComparer.OrdinalIgnoreCase)
  77. .ToList();
  78. foreach (var item in artists)
  79. {
  80. var index = GetIndex(item, searchTerm, terms);
  81. if (index.Item2 != -1)
  82. {
  83. try
  84. {
  85. var artist = _libraryManager.GetArtist(item);
  86. hints.Add(new Tuple<BaseItem, string, int>(artist, index.Item1, index.Item2));
  87. }
  88. catch (Exception ex)
  89. {
  90. _logger.ErrorException("Error getting {0}", ex, item);
  91. }
  92. }
  93. }
  94. // Find genres, from non-audio items
  95. var genres = items.Where(i => !(i is IHasMusicGenres) && !(i is Game))
  96. .SelectMany(i => i.Genres)
  97. .Where(i => !string.IsNullOrEmpty(i))
  98. .Distinct(StringComparer.OrdinalIgnoreCase)
  99. .ToList();
  100. foreach (var item in genres)
  101. {
  102. var index = GetIndex(item, searchTerm, terms);
  103. if (index.Item2 != -1)
  104. {
  105. try
  106. {
  107. var genre = _libraryManager.GetGenre(item);
  108. hints.Add(new Tuple<BaseItem, string, int>(genre, index.Item1, index.Item2));
  109. }
  110. catch (Exception ex)
  111. {
  112. _logger.ErrorException("Error getting {0}", ex, item);
  113. }
  114. }
  115. }
  116. // Find music genres
  117. var musicGenres = items.Where(i => i is IHasMusicGenres)
  118. .SelectMany(i => i.Genres)
  119. .Where(i => !string.IsNullOrEmpty(i))
  120. .Distinct(StringComparer.OrdinalIgnoreCase)
  121. .ToList();
  122. foreach (var item in musicGenres)
  123. {
  124. var index = GetIndex(item, searchTerm, terms);
  125. if (index.Item2 != -1)
  126. {
  127. try
  128. {
  129. var genre = _libraryManager.GetMusicGenre(item);
  130. hints.Add(new Tuple<BaseItem, string, int>(genre, index.Item1, index.Item2));
  131. }
  132. catch (Exception ex)
  133. {
  134. _logger.ErrorException("Error getting {0}", ex, item);
  135. }
  136. }
  137. }
  138. // Find music genres
  139. var gameGenres = items.OfType<Game>()
  140. .SelectMany(i => i.Genres)
  141. .Where(i => !string.IsNullOrEmpty(i))
  142. .Distinct(StringComparer.OrdinalIgnoreCase)
  143. .ToList();
  144. foreach (var item in gameGenres)
  145. {
  146. var index = GetIndex(item, searchTerm, terms);
  147. if (index.Item2 != -1)
  148. {
  149. try
  150. {
  151. var genre = _libraryManager.GetGameGenre(item);
  152. hints.Add(new Tuple<BaseItem, string, int>(genre, index.Item1, index.Item2));
  153. }
  154. catch (Exception ex)
  155. {
  156. _logger.ErrorException("Error getting {0}", ex, item);
  157. }
  158. }
  159. }
  160. // Find studios
  161. var studios = items.SelectMany(i => i.Studios)
  162. .Where(i => !string.IsNullOrEmpty(i))
  163. .Distinct(StringComparer.OrdinalIgnoreCase)
  164. .ToList();
  165. foreach (var item in studios)
  166. {
  167. var index = GetIndex(item, searchTerm, terms);
  168. if (index.Item2 != -1)
  169. {
  170. try
  171. {
  172. var studio = _libraryManager.GetStudio(item);
  173. hints.Add(new Tuple<BaseItem, string, int>(studio, index.Item1, index.Item2));
  174. }
  175. catch (Exception ex)
  176. {
  177. _logger.ErrorException("Error getting {0}", ex, item);
  178. }
  179. }
  180. }
  181. // Find persons
  182. var persons = items.SelectMany(i => i.People)
  183. .Select(i => i.Name)
  184. .Where(i => !string.IsNullOrEmpty(i))
  185. .Distinct(StringComparer.OrdinalIgnoreCase)
  186. .ToList();
  187. foreach (var item in persons)
  188. {
  189. var index = GetIndex(item, searchTerm, terms);
  190. if (index.Item2 != -1)
  191. {
  192. try
  193. {
  194. var person = _libraryManager.GetPerson(item);
  195. hints.Add(new Tuple<BaseItem, string, int>(person, index.Item1, index.Item2));
  196. }
  197. catch (Exception ex)
  198. {
  199. _logger.ErrorException("Error getting {0}", ex, item);
  200. }
  201. }
  202. }
  203. var returnValue = hints.Where(i => i.Item3 >= 0).OrderBy(i => i.Item3).Select(i => new SearchHintInfo
  204. {
  205. Item = i.Item1,
  206. MatchedTerm = i.Item2
  207. });
  208. return Task.FromResult(returnValue);
  209. }
  210. /// <summary>
  211. /// Gets the index.
  212. /// </summary>
  213. /// <param name="input">The input.</param>
  214. /// <param name="searchInput">The search input.</param>
  215. /// <param name="searchWords">The search input.</param>
  216. /// <returns>System.Int32.</returns>
  217. private Tuple<string, int> GetIndex(string input, string searchInput, List<string> searchWords)
  218. {
  219. if (string.IsNullOrEmpty(input))
  220. {
  221. throw new ArgumentNullException("input");
  222. }
  223. if (string.Equals(input, searchInput, StringComparison.OrdinalIgnoreCase))
  224. {
  225. return new Tuple<string, int>(searchInput, 0);
  226. }
  227. var index = input.IndexOf(searchInput, StringComparison.OrdinalIgnoreCase);
  228. if (index == 0)
  229. {
  230. return new Tuple<string, int>(searchInput, 1);
  231. }
  232. if (index > 0)
  233. {
  234. return new Tuple<string, int>(searchInput, 2);
  235. }
  236. var items = GetWords(input);
  237. for (var i = 0; i < searchWords.Count; i++)
  238. {
  239. var searchTerm = searchWords[i];
  240. for (var j = 0; j < items.Count; j++)
  241. {
  242. var item = items[j];
  243. if (string.Equals(item, searchTerm, StringComparison.OrdinalIgnoreCase))
  244. {
  245. return new Tuple<string, int>(searchTerm, 3 + (i + 1) * (j + 1));
  246. }
  247. index = item.IndexOf(searchTerm, StringComparison.OrdinalIgnoreCase);
  248. if (index == 0)
  249. {
  250. return new Tuple<string, int>(searchTerm, 4 + (i + 1) * (j + 1));
  251. }
  252. if (index > 0)
  253. {
  254. return new Tuple<string, int>(searchTerm, 5 + (i + 1) * (j + 1));
  255. }
  256. }
  257. }
  258. return new Tuple<string, int>(null, -1);
  259. }
  260. /// <summary>
  261. /// Gets the words.
  262. /// </summary>
  263. /// <param name="term">The term.</param>
  264. /// <returns>System.String[][].</returns>
  265. private List<string> GetWords(string term)
  266. {
  267. return term.Split().Where(i => !string.IsNullOrWhiteSpace(i)).ToList();
  268. }
  269. }
  270. }