PageRenderTime 43ms CodeModel.GetById 11ms RepoModel.GetById 1ms app.codeStats 0ms

Java | 241 lines | 196 code | 38 blank | 7 comment | 4 complexity | 225bca6a8c1e3ca0dbe4fe08cad04ceb MD5 | raw file
  1. package;
  2. import;
  3. import;
  4. import;
  5. import java.util.Arrays;
  6. import java.util.Collection;
  7. import java.util.List;
  8. import;
  9. import;
  10. import org.apache.lucene.analysis.standard.StandardAnalyzer;
  11. import org.apache.lucene.document.Document;
  12. import org.apache.lucene.document.Field;
  13. import org.apache.lucene.document.StringField;
  14. import org.apache.lucene.document.TextField;
  15. import org.apache.lucene.index.DirectoryReader;
  16. import org.apache.lucene.index.IndexWriter;
  17. import org.apache.lucene.index.IndexWriterConfig;
  18. import org.apache.lucene.index.IndexWriterConfig.OpenMode;
  19. import org.apache.lucene.queryparser.classic.ParseException;
  20. import org.apache.lucene.queryparser.classic.QueryParser;
  21. import;
  22. import;
  23. import;
  24. import;
  25. import;
  26. import org.apache.lucene.util.Version;
  27. import org.slf4j.Logger;
  28. import org.slf4j.LoggerFactory;
  29. import;
  30. /**
  31. * AShortIntroductionToLucene
  32. * @see
  33. * @author doctor
  34. *
  35. * @time 2015年1月14日 上午10:50:20
  36. */
  37. public class AShortIntroductionToLucene {
  38. public static void main(String[] args) throws Throwable{
  39. String indexDir = AShortIntroductionToLucene.class.getClassLoader().getResource("lucene-tutorial/tempIndexDir").getFile();
  40. Indexer indexer = new Indexer(indexDir);
  41. indexer.indexHotels(HotelDatabase.gethHotels());
  42. indexer.commit();
  43. indexer.close();
  44. SearchEngine searchEngine = new SearchEngine(indexDir);
  45. TopDocs topDocs = searchEngine.serach("Notre Dame museum", 100);
  46. for (ScoreDoc doc : topDocs.scoreDocs) {
  47. Document document = searchEngine.getDocument(doc.doc);
  48. printDocument(document);
  49. }
  50. }
  51. private static void printDocument(Document document){
  52. String content = String.join("\t", document.get(,document.get(,document.get(;
  53. System.out.println(content);
  54. }
  55. private static class Indexer implements Closeable {
  56. private static final Logger log = LoggerFactory.getLogger(Indexer.class);
  57. private IndexWriter indexWriter = null;
  58. public Indexer(String indexDir) throws IOException{
  59. if (indexWriter == null) {
  60. IndexWriterConfig conf = new IndexWriterConfig(Version.LUCENE_4_10_3, new StandardAnalyzer());
  61. conf.setOpenMode(OpenMode.CREATE);
  62. Directory d = File(indexDir));
  63. indexWriter = new IndexWriter(d, conf);
  64. }
  65. }
  66. public void indexHotel(Hotel hotel) throws IOException{
  67."{index hotel:'{}'}",hotel);
  68. Document document = new Document();
  69. document.add(new StringField(, hotel.getId(), Field.Store.YES));
  70. document.add(new StringField(, hotel.getName(), Field.Store.YES));
  71. document.add(new StringField(, hotel.getCity(), Field.Store.YES));
  72. document.add(new TextField(LuceneField.description,
  73. String.join(",", hotel.getId(),hotel.getName(),hotel.getCity(),hotel.getDescription()),
  74. Field.Store.NO));
  75. indexWriter.addDocument(document);
  76. }
  77. public void commit() throws IOException{
  78. indexWriter.commit();
  79. }
  80. public void indexHotels(Collection<Hotel> collection) throws IOException{
  81. for (Hotel hotel : collection) {
  82. indexHotel(hotel);
  83. }
  84. }
  85. @Override
  86. public void close() throws IOException {
  87. IOUtils.closeQuietly(indexWriter);
  88. }
  89. }
  90. private static class SearchEngine{
  91. private IndexSearcher indexSearcher;
  92. private QueryParser queryParser;
  93. public SearchEngine(String indexDir) throws IOException{
  94. indexSearcher = new IndexSearcher( File(indexDir))));
  95. queryParser = new QueryParser(LuceneField.description, new StandardAnalyzer());
  96. }
  97. public TopDocs serach(String query,int n) throws IOException, ParseException{
  98. return, n);
  99. }
  100. public Document getDocument(int docId) throws IOException{
  101. return indexSearcher.doc(docId);
  102. }
  103. }
  104. private interface LuceneField{
  105. String id = "id";
  106. String name = "name";
  107. String city = "city";
  108. String description = "description";
  109. }
  110. private static class Hotel{
  111. private String id;
  112. private String name;
  113. private String city;
  114. private String description;
  115. public Hotel(){
  116. }
  117. public Hotel(String id,String name,String city,String description) {
  118. = id;
  119. = name;
  120. = city;
  121. this.description = description;
  122. }
  123. public String getId() {
  124. return id;
  125. }
  126. public void setId(String id) {
  127. = id;
  128. }
  129. public String getName() {
  130. return name;
  131. }
  132. public void setName(String name) {
  133. = name;
  134. }
  135. public String getCity() {
  136. return city;
  137. }
  138. public void setCity(String city) {
  139. = city;
  140. }
  141. public String getDescription() {
  142. return description;
  143. }
  144. public void setDescription(String description) {
  145. this.description = description;
  146. }
  147. @Override
  148. public String toString() {
  149. return JSON.toJSONString(this);
  150. }
  151. }
  152. private static class HotelDatabase{
  153. private static final List<Hotel> list = Arrays.asList(
  154. new Hotel("1","Hôtel Rivoli","Paris","If you like historical Paris, you will adore the hotel. The hotel is right in the center of the city, right beside the Louvre, residence of the Kings of France during several centuries and, today, the greatest museum in the world."),
  155. new Hotel("2","Hôtel Notre Dame","Paris","Right in the center of the Latin Quarter, in front of the Cathedral, the staff of Hotel Le Notre-Dame,will be delighted to welcome you during your stay in Paris."),
  156. new Hotel("3","Hôtel Trinité","Paris","From the hotel you will find the Galeries Lafayette department store directly opposite, the Opera nearby and the Louvre Museum or Montmartre just a few minutes' stroll away"),
  157. new Hotel("4","Hôtel Delavigne","Paris","Amongst all the picturesque attractions of Paris, there's one the whole world admires : the Latin Quarter."),
  158. new Hotel("5","Hôtel Corail","Paris","Within walking distance from the Gare de Lyon as well as from the Opera-Bastille, the CORAIL HOTEL offers you a warm welcome and a comfortable stay."),
  159. new Hotel("6","Hôtel Edouard VII","Paris","Elegant hotel located in the heart of Paris. It is only a few steps from Louvre Museum, Orsay Museum, Place Vendome and the most famous and prestigious parisian boutiques."),
  160. new Hotel("7","Hôtel Carladez","Paris","This charming hotel is located on a lovely, typically Parisian square. Lively cafôs, restaurants and shops are plenty in this part of the 15th district."),
  161. new Hotel("8","Hôtel Saint Germain","Paris","The Left Bank Hotel benefits from a wonderful location in the heart of the left bank area, which has always attracted artists and intellectuals."),
  162. new Hotel("9","Hôtel Vincennes","Paris","Our traditional hotel is surrounded by the charms of Provence and the elegance of Paris. Chôteau and Bois de Vincennes, Floral Park, race course, Zoo, Disneyland Paris resort (via RER line A)."),
  163. new Hotel("10","Hôtel Bretton","Paris","The Britannique is a genuine charming hotel. Its site, close to Place du chatelet, in the historical center of Paris is ideal for visiting by foot the oldest districts such as the Louvre, les Halles, le Marais, Saint Germain des Prôs and the Latin quarter, the islands of la Citô and Saint Louis ."),
  164. new Hotel("11","Hôtel Cazaudehore","Paris","This spacious, embracing residence, at the edge of the forest and horseback riding paths, just a short walk of the castle where Louis XIV was born, is wrapped in the aroma of roses and the fragrance of the undergrowth, under the changing colours of the Ile de France's sky and the forest's flickering hues."),
  165. new Hotel("12","Hôtel Horset","Paris","Ideally located right in the heart of Paris tourist area, between the Louvre and the Garnier Opera House, close to the Place Vendôme, and the Palais Royal, the recently renovated hotel l'Horset Opera is an oasis of calm in the heart of this bustling district of Paris."),
  166. new Hotel("13","Hôtel Tonic","Paris","Located in the very heart of Paris, within a few steps from the Louvre, Notre Dame and the Champs Elysôes, Tonic Hotel Louvre proposes you its 34 rooms equipped with bathrooms, satellite television and minibar. "),
  167. new Hotel("14","Hôtel Simone","Paris","A perfect location, in the heart of Paris elegant Right Bank : the Louvre, the Palais Royal, rue St Honorô and the Opôra are close by."),
  168. new Hotel("15","Hôtel Odeon","Paris","In the heart of Old Saint-Germain, steps from fhe Odeon theatre, between the Luxembourg Gardens and Notre-Dame, a hotel teeming with charm in a street where quiet prevails: Grand Hôtel des Balcons."),
  169. new Hotel("16","Hôtel Neuilly","Paris","A splendid small hotel with a special charm, refurbished in 2004 and situated in a fashionable part of the city close to the homes of many celebrities, 5 minutes from the Champs Elysôes and the Palais des Congrôs."),
  170. new Hotel("17","Hôtel Chatillon","Paris","Hôtel Chôtillon Montparnasse is situated at the end of a small cul-de-sac, away from the hurly-burly, in the heart of a busy commercial area of the city. "),
  171. new Hotel("18","Hôtel Bellevue","Paris"," We are located a few steps away from Notre-Dame and the Pantheon, in Saint Germain-des-Prôs quarter, in the heart of Paris. There are enough restaurants, cafôs terraces or fashion boutiques and people in the streets to make you appreciate the livingness of this area of the capital."),
  172. new Hotel("19","Hôtel Marais","Paris","Situated at a focus point of the Paris business word and a few minutes walk from many attractive historical and cultural places (Marais, Notre Dame, Centre Pompidou and Louvre Museums...), the new hotel FRANCE EUROPE offers you quietness and a warm hospitality that will make you feel at home."),
  173. new Hotel("20","Hôtel Opéra","Paris","Located in the center of Paris, between Opera and Bourse, near the Louvre in the aera of tourism, shopping and business."),
  174. new Hotel("21","Hôtel Beaugrenelle","Paris","The hotel is located on the left bank, close to the Eiffel Tower,the Champs de Mars, the River Seine and next to the Champs Elysôes, Montparnasse and the exhibition Center Porte de Versailles. Also next to the hotel, ôCap 15ô the business center, the Japanese house of culture and the Unescoô"),
  175. new Hotel("22","Hôtel Italie","Paris"," ldeally located at the heart of the very chic Saint-Germain des Prôs district, the Madison is one of its most distinguished addresses. Discriminating travellers will appreciate its elegance, warm ambiance and attentive, courteous welcome."),
  176. new Hotel("23","Hôtel Trocadero","Paris","Calm and quiet, is ideally located to visit Paris. While leaving your hotel you are on the splendid esplanade of Trocadôro which offers you the most beautiful prospect in town, you cross the Iôna bridge and you are already at the Eiffel Tower."),
  177. new Hotel("24","Hôtel Royal Opéra","Paris","Situated in the heart of the business area, luxurious shops, theaters, hotel Royal Opera has a very good location Next to the Opera and the Madeleine Church, we offer you a lovely and warm atmosphere which will make you delighted."),
  178. new Hotel("25","Hôtel Mermoz","Paris","The world of business meets the universe of fashion and art at the Hôtel Elysôes Mermoz, located between Champs Elysôes and Faubourg Saint Honorô with its luxury boutiques. The 22 rooms and 5 suites offer up to date amenities. "),
  179. new Hotel("26","Albert 1er","Nice","An elegant Riviera-style building facing the sea and floral gardens, the Hotel Albert ler is located in the very heart of Nice, a short walk away from ‘La Vieille Ville’ (Old Town)."),
  180. new Hotel("27","Nice Fleurs","Nice","The three-star residence Nice Fleurs enjoys an ideal location in the centre of Nice, neighbouring the beach and the famous Promenade des Anglais."),
  181. new Hotel("28","Hotel Acropole Nice","Nice","The Hotel Acropole is situated in the heart of Nice, close to the beautiful beaches, the Acropole Conference Center and the shopping area."),
  182. new Hotel("29","Brice Hotel","Nice","A hotel with restaurant of charm in a single Oasis of greenery to the heart of Nice. The Brice hotel guarantees to you a pleasant stay with its cordial garden and its warm reception."),
  183. new Hotel("30","Hôtel Excelsior","Nice","The Excelsior Hotel, constructed in 1898, with a tradition and comfort 'Belle Epoque', offers you the very warmest welcome, with the casual atmosphere of luxury."),
  184. new Hotel("31","Le Pigonnet Hotel","Aix-en-Provenve","Located close to the town center, a 18th century Provencal country house surrounded by a magnificent park from which Cezanne painted the Mount Saint Victoire."),
  185. new Hotel("32","Le Chateau de la Pioline Hotel","Aix-en-Provenve","Magnificent hotel in a beautiful fortified chateau from 16th century by a magnificent park."),
  186. new Hotel("33","Royal Mirabeau Hotel","Aix-en-Provenve","Elegant hotel, surrounded by a beautiful garden and green areas, offering cheerful and comfortable rooms with a view of the pinewood or golf course and St. Victoire mountain."),
  187. new Hotel("34","Aquabella Hotel","Aix-en-Provenve","Comfortable hotel with a wide choice of relaxation facilities, ideally located in the heart of the old town, at the foot of the ancient fortifications."),
  188. new Hotel("35","Mona Lisa Fuveau Hotel","Aix-en-Provenve","Located in Fuveau, the Mona Lisa hotel offers peace and quiet of the Provencal countryside, high-tech equipment, and top-of-the-range service."),
  189. new Hotel("36","Hotellerie Les Frenes Hotel","Avignon","Luxury family run hotel in a superb XIX century residence, surrounded by a hundred years old garden, set close to the Pope's Palace and the Avignon's Bridge."),
  190. new Hotel("37","Les Agassins Hotel","Avignon","Comfortable and friendly hotel decorated with lovely collection of paintings, offering splendid garden and the best restaurant in the region."),
  191. new Hotel("38","Clarion Cloitre Saint Louis Hotel","Avignon","Elegant hotel set in a historic stone cloister, boasting rooms with majestic decorations, overlooking tree-filled garden, or the rooftops, monuments and Museum of Avignon, located close to the city center."),
  192. new Hotel("39","Auberge de Cassagne Hotel","Avignon","Situated on the edge of Avignon, hidden in an oasis of green gardens and refreshing fountains, the Auberge de Cassagne, of a refined architectural style, is housed in a former bastide dating from 1850."),
  193. new Hotel("40"," Grand Hotel","Avignon"," New hotel complex, offering comfortable, elegant and spacious suites and apartments, facing the old city ramparts, just steps away from the center of Avignon.")
  194. );
  195. public static List<Hotel> gethHotels(){
  196. return list;
  197. }
  198. public static Hotel getHotelById(String id){
  199. List<Hotel> collect = ->;
  200. return collect.isEmpty()?null:collect.get(0);
  201. }
  202. }
  203. }