search
HomeDatabaseMysql TutorialLucene 索引数据库

Lucene 索引数据库

Jun 07, 2016 pm 03:35 PM
lucenehowdatabaseCompareclearindex

本文比较清晰的介绍了怎样将数据从db转到lucene索引文件。同样可以参照车东的博客: http://www.chedong.com/tech/weblucene.html 这篇。 Lucene,作为一种全文搜索的辅助工具,为我们进行条件搜索,无论是像Google,Baidu之类的搜索引擎,还是论坛中的搜索功

本文比较清晰的介绍了怎样将数据从db转到lucene索引文件。同样可以参照车东的博客:
http://www.chedong.com/tech/weblucene.html
这篇。

Lucene,作为一种全文搜索的辅助工具,为我们进行条件搜索,无论是像Google,Baidu之类的搜索引擎,还是论坛中的搜索功能,还是其它 C/S架构的搜索,都带来了极大的便利和比较高的效率。本文主要是利用Lucene对MS Sql Server 2000进行建立索引,然后进行全文搜索。至于数据库的内容,可以是网页的内容,还是其它的。本文中数据库的内容是图书馆管理系统中的某个作者表- Authors表。

  因为考虑到篇幅的问题,所以该文不会讲的很详细,也不可能讲的很深。

  本文以这样的结构进行:

  1.介绍数据库中Authors表的结构

  2.为数据库建立索引

  3.为数据库建立查询功能

  4.在web界面下进行查询并显示结果

1.介绍数据库中Authors表的结构

字段名称         字段类型         字段含义

Au_id                Varchar(11)    作者号
Au_name        Varchar(60)     作者名
Phone             Char(12)           电话号码
Address          Varchar(40)      地址
City                   Varchar(20)     城市
State                Char(2)             省份
Zip                    Char(5)             邮编
contract            Bit(1)                外键(关系不大)

表中的部分内容:
 
2.为数据库建立索引

  首先建立一个类TestLucene.java。这个类就是对数据库进行建立索引,编写查询条件等。

  当然,最开始就是建立数据库连接。连接代码这里就省略了。^_^

  接着,新建一个方法getResutl(String),它返回的是数据库表Authors的内容。具体代码如下:


    public ResultSet getResult(String sql){
      try{
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(sql);
        return rs;
      }
      catch(SQLException e){
        System.out.println(e);
      }
      return null;
    }
 
  然后,为数据库建立索引。

   首先要定义一个IndexWriter(),它是将索引写进Lucene自己的数据库中,它存放的位置是你自己定义的。在定义IndexWriter是 需要指定它的分析器。Lucene自己自带有几个分析器,例如:StandarAnalyzer(),SimpleAnalyzer(), StopAnalyzer()等。它作用是对文本进行分析,判断如何进行切词。

        接着,要定义一个Document。Document相当于二维表中一行数据一样。Document里包含的是Field字段,Field相当于数据库中 一列,也就是一个属性,一个字段。最后应该对IndexWriter进行优化,方法很简单,就是writer.optimize().
具体代码如下:
  public void Index(ResultSet rs){
      try{
        IndexWriter writer = new IndexWriter("d:/index/", getAnalyzer(), true);
        while(rs.next()){
            Document doc=new Document();
            doc.add(Field.Keyword("id",rs.getString("au_id")));
            doc.add(Field.Text("name",rs.getString("au_name")));
            doc.add(Field.UnIndexed("address",rs.getString("address")));
            doc.add(Field.UnIndexed("phone",rs.getString("phone")));
            doc.add(Field.Text("City",rs.getString("city")));
            writer.addDocument(doc);
          }
        writer.optimize();
        writer.close();
      }
      catch(IOException e){
        System.out.println(e);
      }
      catch(SQLException e){
        System.out.println(e);
      }
    }

    public Analyzer getAnalyzer(){
      return new StandardAnalyzer();
    }

  3.为数据库建立查询功能

  在类TestLucene中建立一个新的方法searcher(String),它返回的是一个搜索的结构集,相当于数据库中的ResultSet一样。它代的参数是你要查询的内容。这里,我把要查询的字段写死了。你可以在添加一个参数表示要查询的字段。
       这里主要有两个对象IndexSearcher和Query。IndexSearcher是找到索引数据库,Query是处理搜索,它包含了三个参数:查询内容,查询字段,分析器。
具体代码如下:


  public Hits seacher(String queryString){
      Hits hits=null;;
      try{
        IndexSearcher is = new IndexSearcher("D:/index/");
        Query query=QueryParser.parse(queryString,"City",getAnalyzer());
        hits=is.search(query);
      }catch(Exception e){
        System.out.print(e);
      }
      return hits;
    }
 
  4.在web界面下进行查询并显示结果

  这里建立一个Jsp页面TestLucene.jsp进行搜索。

  在TestLucene.jsp页面中首先引入类


 
  然后定义一个LuceneTest对象,获取查询结果集:
        LucentTest lucent=new LucentTest();
        Hits hits=lucent.seacher(request.getParameter("queryString"));
 
  定义一个Form,建立一个查询环境:


 
 

 
  显示查询结果:



 
 
   
   
   
   
   
    Document doc=hits.doc(i);
   %>
   

   
   
   
   
 
 
作者号 作者名 地址 电话号码
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain the role of InnoDB redo logs and undo logs.Explain the role of InnoDB redo logs and undo logs.Apr 15, 2025 am 12:16 AM

InnoDB uses redologs and undologs to ensure data consistency and reliability. 1.redologs record data page modification to ensure crash recovery and transaction persistence. 2.undologs records the original data value and supports transaction rollback and MVCC.

What are the key metrics to look for in an EXPLAIN output (type, key, rows, Extra)?What are the key metrics to look for in an EXPLAIN output (type, key, rows, Extra)?Apr 15, 2025 am 12:15 AM

Key metrics for EXPLAIN commands include type, key, rows, and Extra. 1) The type reflects the access type of the query. The higher the value, the higher the efficiency, such as const is better than ALL. 2) The key displays the index used, and NULL indicates no index. 3) rows estimates the number of scanned rows, affecting query performance. 4) Extra provides additional information, such as Usingfilesort prompts that it needs to be optimized.

What is the Using temporary status in EXPLAIN and how to avoid it?What is the Using temporary status in EXPLAIN and how to avoid it?Apr 15, 2025 am 12:14 AM

Usingtemporary indicates that the need to create temporary tables in MySQL queries, which are commonly found in ORDERBY using DISTINCT, GROUPBY, or non-indexed columns. You can avoid the occurrence of indexes and rewrite queries and improve query performance. Specifically, when Usingtemporary appears in EXPLAIN output, it means that MySQL needs to create temporary tables to handle queries. This usually occurs when: 1) deduplication or grouping when using DISTINCT or GROUPBY; 2) sort when ORDERBY contains non-index columns; 3) use complex subquery or join operations. Optimization methods include: 1) ORDERBY and GROUPB

Describe the different SQL transaction isolation levels (Read Uncommitted, Read Committed, Repeatable Read, Serializable) and their implications in MySQL/InnoDB.Describe the different SQL transaction isolation levels (Read Uncommitted, Read Committed, Repeatable Read, Serializable) and their implications in MySQL/InnoDB.Apr 15, 2025 am 12:11 AM

MySQL/InnoDB supports four transaction isolation levels: ReadUncommitted, ReadCommitted, RepeatableRead and Serializable. 1.ReadUncommitted allows reading of uncommitted data, which may cause dirty reading. 2. ReadCommitted avoids dirty reading, but non-repeatable reading may occur. 3.RepeatableRead is the default level, avoiding dirty reading and non-repeatable reading, but phantom reading may occur. 4. Serializable avoids all concurrency problems but reduces concurrency. Choosing the appropriate isolation level requires balancing data consistency and performance requirements.

MySQL vs. Other Databases: Comparing the OptionsMySQL vs. Other Databases: Comparing the OptionsApr 15, 2025 am 12:08 AM

MySQL is suitable for web applications and content management systems and is popular for its open source, high performance and ease of use. 1) Compared with PostgreSQL, MySQL performs better in simple queries and high concurrent read operations. 2) Compared with Oracle, MySQL is more popular among small and medium-sized enterprises because of its open source and low cost. 3) Compared with Microsoft SQL Server, MySQL is more suitable for cross-platform applications. 4) Unlike MongoDB, MySQL is more suitable for structured data and transaction processing.

How does MySQL index cardinality affect query performance?How does MySQL index cardinality affect query performance?Apr 14, 2025 am 12:18 AM

MySQL index cardinality has a significant impact on query performance: 1. High cardinality index can more effectively narrow the data range and improve query efficiency; 2. Low cardinality index may lead to full table scanning and reduce query performance; 3. In joint index, high cardinality sequences should be placed in front to optimize query.

MySQL: Resources and Tutorials for New UsersMySQL: Resources and Tutorials for New UsersApr 14, 2025 am 12:16 AM

The MySQL learning path includes basic knowledge, core concepts, usage examples, and optimization techniques. 1) Understand basic concepts such as tables, rows, columns, and SQL queries. 2) Learn the definition, working principles and advantages of MySQL. 3) Master basic CRUD operations and advanced usage, such as indexes and stored procedures. 4) Familiar with common error debugging and performance optimization suggestions, such as rational use of indexes and optimization queries. Through these steps, you will have a full grasp of the use and optimization of MySQL.

Real-World MySQL: Examples and Use CasesReal-World MySQL: Examples and Use CasesApr 14, 2025 am 12:15 AM

MySQL's real-world applications include basic database design and complex query optimization. 1) Basic usage: used to store and manage user data, such as inserting, querying, updating and deleting user information. 2) Advanced usage: Handle complex business logic, such as order and inventory management of e-commerce platforms. 3) Performance optimization: Improve performance by rationally using indexes, partition tables and query caches.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.