Lucene-14万条产品数据

  1.  14万条数据
    在前面的 入门 里是用了10条记录来测试,实际情况肯定是不会只有10条记录了,所以为了模仿真实环境,花了很多精力,四处搜刮来了14万条天猫的产品数据,接下来我们就会把这14万条记录加入到 Lucene,然后观察搜索效果。
  2.  关于数据库
    本来应该先把这14万条记录保存进数据库,然后再从数据库中取出来的,不过改成直接从文件里读取出来,然后转换为泛型是Product的集合的形式,相当于从数据库里读取出来了,不过会快很多。
  3.  140k_products.txt
    首先下载 140k_products.rar,并解压为140k_products.txt, 然后放在项目目录下。 这个文件里一共有14万条产品记录。
  4.  Product.java
    准备实体类来存放产品信息
    public class Product {
     
        int id;
        String name;
        String category;
        float price;
        String place;
     
        String code;
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getCategory() {
            return category;
        }
        public void setCategory(String category) {
            this.category = category;
        }
        public float getPrice() {
            return price;
        }
        public void setPrice(float price) {
            this.price = price;
        }
        public String getPlace() {
            return place;
        }
        public void setPlace(String place) {
            this.place = place;
        }
     
        public String getCode() {
            return code;
        }
        public void setCode(String code) {
            this.code = code;
        }
        @Override
        public String toString() {
            return "Product [id=" + id + ", name=" + name + ", category=" + category + ", price=" + price + ", place="
                    + place + ", code=" + code + "]";
        }
     
    }
  5.  ProductUtil.java
    准备工具类,把140k_products.txt 文本文件,转换为泛型是Product的集合
    public class ProductUtil {
         
        public static void main(String[] args) throws IOException, InterruptedException, AWTException {
     
            String fileName = "140k_products.txt";
             
            List<Product> products = file2list(fileName);
             
            System.out.println(products.size());
                 
        }
     
        public static List<Product> file2list(String fileName) throws IOException {
            File f = new File(fileName);
            List<String> lines = FileUtils.readLines(f,"UTF-8");
            List<Product> products = new ArrayList<>();
            for (String line : lines) {
                Product p = line2product(line);
                products.add(p);
            }
            return products;
        }
         
        private static Product line2product(String line) {
            Product p = new Product();
            String[] fields = line.split(",");
            p.setId(Integer.parseInt(fields[0]));
            p.setName(fields[1]);
            p.setCategory(fields[2]);
            p.setPrice(Float.parseFloat(fields[3]));
            p.setPlace(fields[4]);
            p.setCode(fields[5]);
            return p;
        }
     
    }
  6.  TestLucene.java
    在入门中 TestLucene.java 的基础上进行修改。 主要做了两个方面的修改:
    1. 索引的增加,以前是10条数据,现在是14万条数据
    注: 因为数据量比较大, 所以加入到索引的时间也比较久,请耐心等待。
    2. Document以前只有name字段,现在有6个字段
    3. 查询关键字从控制台输入,这样每次都可以输入不同的关键字进行查询。 因为索引建立时间比较久,采用这种方式,可以建立一次索引,进行多次查询,否则的话,每次使用不同的关键字,都要耗时建立索引,测试效率会比较低
    public class TestLucene {
     
        public static void main(String[] args) throws Exception {
            // 1. 准备中文分词器
            IKAnalyzer analyzer = new IKAnalyzer();
            // 2. 索引
            Directory index = createIndex(analyzer);
     
            // 3. 查询器
             
            Scanner s = new Scanner(System.in);
             
            while(true){
                System.out.print("请输入查询关键字:");
                String keyword = s.nextLine();
                System.out.println("当前关键字是:"+keyword);
                Query query = new QueryParser( "name", analyzer).parse(keyword);
     
                // 4. 搜索
                IndexReader reader = DirectoryReader.open(index);
                IndexSearcher searcher=new IndexSearcher(reader);
                int numberPerPage = 10;
                ScoreDoc[] hits = searcher.search(query, numberPerPage).scoreDocs;
                 
                // 5. 显示查询结果
                showSearchResults(searcher, hits,query,analyzer);
                // 6. 关闭查询
                reader.close();
            }
             
        }
     
        private static void showSearchResults(IndexSearcher searcher, ScoreDoc[] hits, Query query, IKAnalyzer analyzer) throws Exception {
            System.out.println("找到 " + hits.length + " 个命中.");
     
            SimpleHTMLFormatter simpleHTMLFormatter = new SimpleHTMLFormatter("<span style='color:red'>", "</span>");
            Highlighter highlighter = new Highlighter(simpleHTMLFormatter, new QueryScorer(query));
     
            System.out.println("找到 " + hits.length + " 个命中.");
            System.out.println("序号\t匹配度得分\t结果");
            for (int i = 0; i < hits.length; ++i) {
                ScoreDoc scoreDoc= hits[i];
                int docId = scoreDoc.doc;
                Document d = searcher.doc(docId);
                List<IndexableField> fields= d.getFields();
                System.out.print((i + 1) );
                System.out.print("\t" + scoreDoc.score);
                for (IndexableField f : fields) {
     
                    if("name".equals(f.name())){
                        TokenStream tokenStream = analyzer.tokenStream(f.name(), new StringReader(d.get(f.name())));
                        String fieldContent = highlighter.getBestFragment(tokenStream, d.get(f.name()));
                        System.out.print("\t"+fieldContent);
                    }
                    else{
                        System.out.print("\t"+d.get(f.name()));
                    }
                }
                System.out.println("<br>");
            }
        }
     
        private static Directory createIndex(IKAnalyzer analyzer) throws IOException {
            Directory index = new RAMDirectory();
            IndexWriterConfig config = new IndexWriterConfig(analyzer);
            IndexWriter writer = new IndexWriter(index, config);
            String fileName = "140k_products.txt";
            List<Product> products = ProductUtil.file2list(fileName);
            int total = products.size();
            int count = 0;
            int per = 0;
            int oldPer =0;
            for (Product p : products) {
                addDoc(writer, p);
                count++;
                per = count*100/total;
                if(per!=oldPer){
                    oldPer = per;
                    System.out.printf("索引中,总共要添加 %d 条记录,当前添加进度是: %d%% %n",total,per);
                }
                 
            }
            writer.close();
            return index;
        }
     
        private static void addDoc(IndexWriter w, Product p) throws IOException {
            Document doc = new Document();
            doc.add(new TextField("id", String.valueOf(p.getId()), Field.Store.YES));
            doc.add(new TextField("name", p.getName(), Field.Store.YES));
            doc.add(new TextField("category", p.getCategory(), Field.Store.YES));
            doc.add(new TextField("price", String.valueOf(p.getPrice()), Field.Store.YES));
            doc.add(new TextField("place", p.getPlace(), Field.Store.YES));
            doc.add(new TextField("code", p.getCode(), Field.Store.YES));
            w.addDocument(doc);
        }
    }

















  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java Lucene-Core 是 Apache Lucene 项目的核心依赖库。Lucene 是一个开源的全文检索引擎工具包,提供了强大的全文检索功能,可用于构建各种基于文本的应用程序。 在使用 Lucene 时,需要添加 Lucene-Core 依赖到项目中,以便能够使用 Lucene 提供的各种功能。Lucene-Core 是 Lucene 项目最基本的依赖库,包含了一些必备的类和方法,用于索引和搜索文档。 通过 Lucene-Core,可以使用 Lucene 提供的各种 API 来创建索引、搜索和加权查询。Lucene 使用倒排索引的方式来快速定位包含搜索词的文档,而不需要遍历整个文档集合。这种索引结构使得 Lucene 具有出色的搜索效率和性能。 Lucene-Core 还提供了各种分析器(Analyzer)和查询解析器(Query Parser),用于处理文本的分词、词干处理和查询解析等操作。分析器可用于将文本分割成词语,并根据需要进行一些文本处理操作。查询解析器则用于将用户的查询语句解析成 Lucene 可以理解的查询对象。 除了 Lucene-Core,还存在其他的 Lucene 依赖库,如 Lucene-Analyzers、Lucene-Queries 等,它们提供了更高级的功能和扩展,用于处理多语言分词、模糊查询、范围查询等等。 总之,Java Lucene-Core 依赖是使用 Lucene 的必备库,它提供了构建全文检索应用程序所需的基本功能和工具。通过使用 Lucene-Core,开发人员可以更方便地利用 Lucene 的强大功能来实现高效的全文检索。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值