LuceneSearchEngine.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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. .Distinct(StringComparer.OrdinalIgnoreCase)
  76. .ToList();
  77. foreach (var item in artists)
  78. {
  79. var index = GetIndex(item, searchTerm, terms);
  80. if (index.Item2 != -1)
  81. {
  82. try
  83. {
  84. var artist = _libraryManager.GetArtist(item);
  85. hints.Add(new Tuple<BaseItem, string, int>(artist, index.Item1, index.Item2));
  86. }
  87. catch (Exception ex)
  88. {
  89. _logger.ErrorException("Error getting {0}", ex, item);
  90. }
  91. }
  92. }
  93. // Find genres, from non-audio items
  94. var genres = items.Where(i => !(i is IHasMusicGenres) && !(i is Game))
  95. .SelectMany(i => i.Genres)
  96. .Where(i => !string.IsNullOrEmpty(i))
  97. .Distinct(StringComparer.OrdinalIgnoreCase)
  98. .ToList();
  99. foreach (var item in genres)
  100. {
  101. var index = GetIndex(item, searchTerm, terms);
  102. if (index.Item2 != -1)
  103. {
  104. try
  105. {
  106. var genre = _libraryManager.GetGenre(item);
  107. hints.Add(new Tuple<BaseItem, string, int>(genre, index.Item1, index.Item2));
  108. }
  109. catch (Exception ex)
  110. {
  111. _logger.ErrorException("Error getting {0}", ex, item);
  112. }
  113. }
  114. }
  115. // Find music genres
  116. var musicGenres = items.Where(i => i is IHasMusicGenres)
  117. .SelectMany(i => i.Genres)
  118. .Where(i => !string.IsNullOrEmpty(i))
  119. .Distinct(StringComparer.OrdinalIgnoreCase)
  120. .ToList();
  121. foreach (var item in musicGenres)
  122. {
  123. var index = GetIndex(item, searchTerm, terms);
  124. if (index.Item2 != -1)
  125. {
  126. try
  127. {
  128. var genre = _libraryManager.GetMusicGenre(item);
  129. hints.Add(new Tuple<BaseItem, string, int>(genre, index.Item1, index.Item2));
  130. }
  131. catch (Exception ex)
  132. {
  133. _logger.ErrorException("Error getting {0}", ex, item);
  134. }
  135. }
  136. }
  137. // Find music genres
  138. var gameGenres = items.OfType<Game>()
  139. .SelectMany(i => i.Genres)
  140. .Where(i => !string.IsNullOrEmpty(i))
  141. .Distinct(StringComparer.OrdinalIgnoreCase)
  142. .ToList();
  143. foreach (var item in gameGenres)
  144. {
  145. var index = GetIndex(item, searchTerm, terms);
  146. if (index.Item2 != -1)
  147. {
  148. try
  149. {
  150. var genre = _libraryManager.GetGameGenre(item);
  151. hints.Add(new Tuple<BaseItem, string, int>(genre, index.Item1, index.Item2));
  152. }
  153. catch (Exception ex)
  154. {
  155. _logger.ErrorException("Error getting {0}", ex, item);
  156. }
  157. }
  158. }
  159. // Find studios
  160. var studios = items.SelectMany(i => i.Studios)
  161. .Where(i => !string.IsNullOrEmpty(i))
  162. .Distinct(StringComparer.OrdinalIgnoreCase)
  163. .ToList();
  164. foreach (var item in studios)
  165. {
  166. var index = GetIndex(item, searchTerm, terms);
  167. if (index.Item2 != -1)
  168. {
  169. try
  170. {
  171. var studio = _libraryManager.GetStudio(item);
  172. hints.Add(new Tuple<BaseItem, string, int>(studio, index.Item1, index.Item2));
  173. }
  174. catch (Exception ex)
  175. {
  176. _logger.ErrorException("Error getting {0}", ex, item);
  177. }
  178. }
  179. }
  180. // Find persons
  181. var persons = items.SelectMany(i => i.People)
  182. .Select(i => i.Name)
  183. .Where(i => !string.IsNullOrEmpty(i))
  184. .Distinct(StringComparer.OrdinalIgnoreCase)
  185. .ToList();
  186. foreach (var item in persons)
  187. {
  188. var index = GetIndex(item, searchTerm, terms);
  189. if (index.Item2 != -1)
  190. {
  191. try
  192. {
  193. var person = _libraryManager.GetPerson(item);
  194. hints.Add(new Tuple<BaseItem, string, int>(person, index.Item1, index.Item2));
  195. }
  196. catch (Exception ex)
  197. {
  198. _logger.ErrorException("Error getting {0}", ex, item);
  199. }
  200. }
  201. }
  202. var returnValue = hints.Where(i => i.Item3 >= 0).OrderBy(i => i.Item3).Select(i => new SearchHintInfo
  203. {
  204. Item = i.Item1,
  205. MatchedTerm = i.Item2
  206. });
  207. return Task.FromResult(returnValue);
  208. }
  209. /// <summary>
  210. /// Gets the index.
  211. /// </summary>
  212. /// <param name="input">The input.</param>
  213. /// <param name="searchInput">The search input.</param>
  214. /// <param name="searchWords">The search input.</param>
  215. /// <returns>System.Int32.</returns>
  216. private Tuple<string, int> GetIndex(string input, string searchInput, List<string> searchWords)
  217. {
  218. if (string.IsNullOrEmpty(input))
  219. {
  220. throw new ArgumentNullException("input");
  221. }
  222. if (string.Equals(input, searchInput, StringComparison.OrdinalIgnoreCase))
  223. {
  224. return new Tuple<string, int>(searchInput, 0);
  225. }
  226. var index = input.IndexOf(searchInput, StringComparison.OrdinalIgnoreCase);
  227. if (index == 0)
  228. {
  229. return new Tuple<string, int>(searchInput, 1);
  230. }
  231. if (index > 0)
  232. {
  233. return new Tuple<string, int>(searchInput, 2);
  234. }
  235. var items = GetWords(input);
  236. for (var i = 0; i < searchWords.Count; i++)
  237. {
  238. var searchTerm = searchWords[i];
  239. for (var j = 0; j < items.Count; j++)
  240. {
  241. var item = items[j];
  242. if (string.Equals(item, searchTerm, StringComparison.OrdinalIgnoreCase))
  243. {
  244. return new Tuple<string, int>(searchTerm, 3 + (i + 1) * (j + 1));
  245. }
  246. index = item.IndexOf(searchTerm, StringComparison.OrdinalIgnoreCase);
  247. if (index == 0)
  248. {
  249. return new Tuple<string, int>(searchTerm, 4 + (i + 1) * (j + 1));
  250. }
  251. if (index > 0)
  252. {
  253. return new Tuple<string, int>(searchTerm, 5 + (i + 1) * (j + 1));
  254. }
  255. }
  256. }
  257. return new Tuple<string, int>(null, -1);
  258. }
  259. /// <summary>
  260. /// Gets the words.
  261. /// </summary>
  262. /// <param name="term">The term.</param>
  263. /// <returns>System.String[][].</returns>
  264. private List<string> GetWords(string term)
  265. {
  266. return term.Split().Where(i => !string.IsNullOrWhiteSpace(i)).ToList();
  267. }
  268. }
  269. }