lucene(全文搜索)_luceneweb例子

先來看看效果圖:

由於我沒"D:\opt\lucene\index",所以不能搜索出東東...

下載地址:

http://apache.dataguru.cn/lucene/java/2.9.4/

lucene-2.9.4-src.zip (包含源碼)

lucene-2.9.4.zip

項目結構:

=======================================================

源碼部分

=======================================================

/luceneweb/WebContent/configuration.jsp

複製代碼
 1 <!--
 2     Licensed to the Apache Software Foundation (ASF) under one or more
 3     contributor license agreements.  See the NOTICE file distributed with
 4     this work for additional information regarding copyright ownership.
 5     The ASF licenses this file to You under the Apache License, Version 2.0
 6     the "License"); you may not use this file except in compliance with
 7     the License.  You may obtain a copy of the License at
 8  
 9         http://www.apache.org/licenses/LICENSE-2.0
10  
11     Unless required by applicable law or agreed to in writing, software
12     distributed under the License is distributed on an "AS IS" BASIS,
13     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14     See the License for the specific language governing permissions and
15     limitations under the License.
16  -->
17 <%
18 /* Author: Andrew C. Oliver ([email protected]) */
19 String appTitle = "Apache Lucene Example - Intranet Server Search Application";
20 /* make sure you point the below string to the index you created with IndexHTML */
21 String indexLocation = "/opt/lucene/index";
22 String appfooter = "Apache Lucene Template WebApp 1.0";
23 %>
複製代碼

/luceneweb/WebContent/footer.jsp

複製代碼
 1 <!--
 2     Licensed to the Apache Software Foundation (ASF) under one or more
 3     contributor license agreements.  See the NOTICE file distributed with
 4     this work for additional information regarding copyright ownership.
 5     The ASF licenses this file to You under the Apache License, Version 2.0
 6     the "License"); you may not use this file except in compliance with
 7     the License.  You may obtain a copy of the License at
 8  
 9         http://www.apache.org/licenses/LICENSE-2.0
10  
11     Unless required by applicable law or agreed to in writing, software
12     distributed under the License is distributed on an "AS IS" BASIS,
13     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14     See the License for the specific language governing permissions and
15     limitations under the License.
16  -->
17 <% /* Author Andrew C. Oliver ([email protected]) */ %>
18 <p align="center">
19     <%=appfooter%>
20 </p>
21 </body>
22 </html>
複製代碼

/luceneweb/WebContent/header.jsp

複製代碼
 1 <!--
 2     Licensed to the Apache Software Foundation (ASF) under one or more
 3     contributor license agreements.  See the NOTICE file distributed with
 4     this work for additional information regarding copyright ownership.
 5     The ASF licenses this file to You under the Apache License, Version 2.0
 6     the "License"); you may not use this file except in compliance with
 7     the License.  You may obtain a copy of the License at
 8  
 9         http://www.apache.org/licenses/LICENSE-2.0
10  
11     Unless required by applicable law or agreed to in writing, software
12     distributed under the License is distributed on an "AS IS" BASIS,
13     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14     See the License for the specific language governing permissions and
15     limitations under the License.
16  -->
17 <%@include file="configuration.jsp"%>
18 <% /* Author: Andrew C. Oliver ([email protected] */ %>
19 <html>
20 <head>
21     <title><%=appTitle%></title>
22 </head>
23 <body>
24 
25 <p align="center">
26 Welcome to the Lucene Template application. (This is the header)
27 </p>
複製代碼

/luceneweb/WebContent/index.jsp

複製代碼
 1 <!--
 2     Licensed to the Apache Software Foundation (ASF) under one or more
 3     contributor license agreements.  See the NOTICE file distributed with
 4     this work for additional information regarding copyright ownership.
 5     The ASF licenses this file to You under the Apache License, Version 2.0
 6     the "License"); you may not use this file except in compliance with
 7     the License.  You may obtain a copy of the License at
 8  
 9         http://www.apache.org/licenses/LICENSE-2.0
10  
11     Unless required by applicable law or agreed to in writing, software
12     distributed under the License is distributed on an "AS IS" BASIS,
13     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14     See the License for the specific language governing permissions and
15     limitations under the License.
16  -->
17 <%@include file="header.jsp"%>
18 <% /* Author: Andrew C. Oliver ([email protected]) */ %>
19 <center> 
20     <form name="search" action="results.jsp" method="get">
21         <p>
22             <input name="query" size="44"/>&nbsp;Search Criteria
23         </p>
24         <p>
25             <input name="maxresults" size="4" value="100"/>&nbsp;Results Per Page&nbsp;
26             <input type="submit" value="Search"/>
27         </p>
28         </form>
29 </center>
30 <%@include file="footer.jsp"%>
複製代碼

/luceneweb/WebContent/results.jsp

複製代碼
  1 <!--
  2     Licensed to the Apache Software Foundation (ASF) under one or more
  3     contributor license agreements.  See the NOTICE file distributed with
  4     this work for additional information regarding copyright ownership.
  5     The ASF licenses this file to You under the Apache License, Version 2.0
  6     the "License"); you may not use this file except in compliance with
  7     the License.  You may obtain a copy of the License at
  8  
  9         http://www.apache.org/licenses/LICENSE-2.0
 10  
 11     Unless required by applicable law or agreed to in writing, software
 12     distributed under the License is distributed on an "AS IS" BASIS,
 13     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 14     See the License for the specific language governing permissions and
 15     limitations under the License.
 16  -->
 17 <%@ page import="javax.servlet.*, javax.servlet.http.*, java.io.*, org.apache.lucene.analysis.*, org.apache.lucene.analysis.standard.StandardAnalyzer, org.apache.lucene.document.*, org.apache.lucene.index.*, org.apache.lucene.store.*, org.apache.lucene.search.*, org.apache.lucene.queryParser.*, org.apache.lucene.demo.*, org.apache.lucene.demo.html.Entities, java.net.URLEncoder, org.apache.lucene.util.Version"%>
 18 
 19 <%
 20     /*
 21      Author: Andrew C. Oliver, SuperLink Software, Inc. ([email protected])
 22 
 23      This jsp page is deliberatly written in the horrible java directly embedded 
 24      in the page style for an easy and concise demonstration of Lucene.
 25      Due note...if you write pages that look like this...sooner or later
 26      you'll have a maintenance nightmare.  If you use jsps...use taglibs
 27      and beans!  That being said, this should be acceptable for a small
 28      page demonstrating how one uses Lucene in a web app. 
 29 
 30      This is also deliberately overcommented. ;-)
 31 
 32      */
 33 %>
 34 <%!public String escapeHTML(String s) {
 35         s = s.replaceAll("&", "&amp;");
 36         s = s.replaceAll("<", "&lt;");
 37         s = s.replaceAll(">", "&gt;");
 38         s = s.replaceAll("\"", "&quot;");
 39         s = s.replaceAll("'", "&apos;");
 40         return s;
 41     }%>
 42 <%@include file="header.jsp"%>
 43 <%
 44     boolean error = false; //used to control flow for error messages
 45     String indexName = indexLocation; //local copy of the configuration variable
 46     IndexSearcher searcher = null; //the searcher used to open/search the index
 47     Query query = null; //the Query created by the QueryParser
 48     TopDocs hits = null; //the search results
 49     int startindex = 0; //the first index displayed on this page
 50     int maxpage = 50; //the maximum items displayed on this page
 51     String queryString = null; //the query entered in the previous page
 52     String startVal = null; //string version of startindex
 53     String maxresults = null; //string version of maxpage
 54     int thispage = 0; //used for the for/next either maxpage or
 55                         //hits.totalHits - startindex - whichever is
 56                         //less
 57 
 58     try {
 59         IndexReader reader = IndexReader.open(FSDirectory.open(new File(indexName)), true); // only searching, so read-only=true
 60         searcher = new IndexSearcher(reader); //create an indexSearcher for our page
 61                                                 //NOTE: this operation is slow for large
 62                                                 //indices (much slower than the search itself)
 63                                                 //so you might want to keep an IndexSearcher 
 64                                                 //open
 65 
 66     } catch (Exception e) { //any error that happens is probably due
 67                             //to a permission problem or non-existant
 68                             //or otherwise corrupt index
 69 %>
 70 <p>ERROR opening the Index - contact sysadmin!</p>
 71 <p>
 72   Error message:
 73   <%=escapeHTML(e.getMessage())%></p>
 74 <%
 75     error = true; //don't do anything up to the footer
 76     }
 77 %>
 78 <%
 79     if (error == false) { //did we open the index?
 80         queryString = request.getParameter("query"); //get the search criteria
 81         startVal = request.getParameter("startat"); //get the start index
 82         maxresults = request.getParameter("maxresults"); //get max results per page
 83         try {
 84             maxpage = Integer.parseInt(maxresults); //parse the max results first
 85             startindex = Integer.parseInt(startVal); //then the start index  
 86         } catch (Exception e) {
 87         } //we don't care if something happens we'll just start at 0
 88             //or end at 50
 89 
 90         if (queryString == null)
 91             throw new ServletException("no query " + //if you don't have a query then
 92                     "specified"); //you probably played on the 
 93                                     //query string so you get the 
 94                                     //treatment
 95 
 96         Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT); //construct our usual analyzer
 97         try {
 98             QueryParser qp = new QueryParser("contents", analyzer);
 99             query = qp.parse(queryString); //parse the 
100         } catch (ParseException e) { //query and construct the Query
101                                         //object
102                                         //if it's just "operator error"
103                                         //send them a nice error HTML
104 %>
105 <p>
106   Error while parsing query:
107   <%=escapeHTML(e.getMessage())%></p>
108 <%
109     error = true; //don't bother with the rest of
110                             //the page
111         }
112     }
113 %>
114 <%
115     if (error == false && searcher != null) { // if we've had no errors
116                                                 // searcher != null was to handle
117                                                 // a weird compilation bug 
118         thispage = maxpage; // default last element to maxpage
119         hits = searcher.search(query, maxpage + startindex); // run the query 
120         if (hits.totalHits == 0) { // if we got no results tell the user
121 %>
122 <p>I'm sorry I couldn't find what you were looking for.</p>
123 <%
124     error = true; // don't bother with the rest of the
125                             // page
126         }
127     }
128 
129     if (error == false && searcher != null) {
130 %>
131 <table>
132   <tr>
133     <td>Document</td>
134     <td>Summary</td>
135   </tr>
136   <%
137       if ((startindex + maxpage) > hits.totalHits) {
138               thispage = hits.totalHits - startindex; // set the max index to maxpage or last
139           } // actual search result whichever is less
140 
141           for (int i = startindex; i < (thispage + startindex); i++) { // for each element
142   %>
143   <tr>
144     <%
145         Document doc = searcher.doc(hits.scoreDocs[i].doc); //get the next document 
146                 String doctitle = doc.get("title"); //get its title
147                 String url = doc.get("path"); //get its path field
148                 if (url != null && url.startsWith("../webapps/")) { // strip off ../webapps prefix if present
149                     url = url.substring(10);
150                 }
151                 if ((doctitle == null) || doctitle.equals("")) //use the path if it has no title
152                     doctitle = url;
153                 //then output!
154     %>
155     <td><a href="<%=url%>"><%=doctitle%></a></td>
156     <td><%=doc.get("summary")%></td>
157   </tr>
158   <%
159       }
160   %>
161   <%
162       if ((startindex + maxpage) < hits.totalHits) { //if there are more results...display 
163                                                           //the more link
164 
165               String moreurl = "results.jsp?query=" + URLEncoder.encode(queryString) + //construct the "more" link
166                       "&amp;maxresults=" + maxpage + "&amp;startat=" + (startindex + maxpage);
167   %>
168   <tr>
169     <td></td>
170     <td><a href="<%=moreurl%>">More Results>></a></td>
171   </tr>
172   <%
173       }
174   %>
175 </table>
176 
177 <%
178     } //then include our footer.
179     if (searcher != null)
180         searcher.close();
181 %>
182 <%@include file="footer.jsp"%>



本文出處:http://www.cnblogs.com/hongten/archive/2012/11/27/hongten_lucene_luceneweb.html

感謝作者
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章