Lucene之模糊、精确、匹配、范围、多条件查询

Lucene的查询方式很 丰富,对于数值类型的数据,采取TermRangeQuery的方式,对于String类型的,就可以采取TermQuery等,查询方式了,可以通过采取合适的查询方式,检索到数据。Queryparser这个查询方式包含了其他几种查询方式。

 

查询方式

查询方式意义
TermQuery 精确查询
TermRangeQuery 查询一个范围
PrefixQuery 前缀匹配查询
WildcardQuery 通配符查询
BooleanQuery 多条件查询
PhraseQuery 短语查询
FuzzyQuery 模糊查询
Queryparser 万能查询(上面的都可以用这个来查询到)

案例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
package com.yellowcong.demo;
 
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
 
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.IntField;
import org.apache.lucene.document.LongField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.FuzzyQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.NumericRangeQuery;
import org.apache.lucene.search.PhraseQuery;
import org.apache.lucene.search.PrefixQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.WildcardQuery;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
 
/**
 * 创建用户:狂飙的yellowcong<br/>
 * 创建时间:下午5:27:50<br/>
 * 创建日期:2017年12月2日<br/>
 * 机能概要:
 */
public class Demo4 {
    private static List<Passage> psgList = null;
 
    // 写对象
    private static IndexWriter writer = null;
 
    public static void main(String[] args) throws Exception {
 
        // 删除 所有索引
        deleteAll();
 
        // 建立索引
        index();
 
        //精确String 类型查询
        getByTermQuery();
 
        //范围查询
        getByRange();
 
        //前缀匹配查询
        getByPrefix();
 
        //通配符查询
        getByWildcard();
 
        //短语查询
        getByPhrase();
 
        //模糊查询
        getByFuzzy();
    }
 
    /**
     * 创建用户:狂飙的yellowcong<br/>
     * 创建日期:2017年12月3日<br/>
     * 创建时间:下午12:00:43<br/>
     * 机能概要:精确查询
     * @throws Exception
     */
    public static void getByTermQuery() {
        System.out.println("-------------查询用户名为yellowcong的数据-------------");
        //精确查询,根据名称来直接
        Query query = new TermQuery(new Term("username", "yellowcong"));
 
        //执行查询
        excQuery(query);
    }
 
    /**
     * 创建用户:狂飙的yellowcong<br/>
     * 创建日期:2017年12月3日<br/>
     * 创建时间:下午12:25:21<br/>
     * 机能概要:范围查询
     */
    public static void getByRange(){
        //精确查询
        System.out.println("-------------查询id在1-3的数据-------------");
        //查询前三条数据,后面两个true,表示的是是否包含头和尾
        Query query = NumericRangeQuery.newIntRange("id", 1, 3, true, true);
        //执行查询
        excQuery(query);
    }
 
    /**
     * 创建用户:狂飙的yellowcong<br/>
     * 创建日期:2017年12月3日<br/>
     * 创建时间:下午12:25:56<br/>
     * 机能概要:前缀查询数据
     */
    public static void getByPrefix(){
        System.out.println("-------------查询前缀 邮箱 以z开头的数据-------------");
        //查询前缀 邮箱 以z开头的数据
        Query query = new PrefixQuery(new Term("email", "z"));
 
        //执行查询
        excQuery(query);
    }
 
    /**
     * 创建用户:狂飙的yellowcong<br/>
     * 创建日期:2017年12月3日<br/>
     * 创建时间:下午12:29:55<br/>
     * 机能概要:通配符查询数据
     */
    public static void getByWildcard(){
        //通配符就更简单了,只要知道“*”表示0到多个字符,而使用“?”表示一个字符就行了
        System.out.println("-------------------查询email 以 @qq结尾的数据--------------");
        //查询email 以 @qq结尾的数据
        Query query = new WildcardQuery(new Term("email","*@qq.com"));
        //执行查询
        excQuery(query);
    }
 
    /**
     * 创建用户:狂飙的yellowcong<br/>
     * 创建日期:2017年12月3日<br/>
     * 创建时间:下午12:43:43<br/>
     * 机能概要:短语查询,查询中间有几个单词的那种
     */
    public static void getByPhrase(){
        System.out.println("------------查询内容中,有I LOVE YOU 的数据---------------");
        //短语查询,但是对于中文没有太多的用,其中查询的时候还有
        PhraseQuery query = new PhraseQuery();
        //设定有几跳,表示中间存在一个单词
        query.setSlop(1);
        //查询
        query.add(new Term("content","i"));
 
        //I  XX you  就可以被查询出来
        query.add(new Term("content","you"));
 
        excQuery(query);
    }
 
    /**
     * 创建用户:狂飙的yellowcong<br/>
     * 创建日期:2017年12月3日<br/>
     * 创建时间:下午12:49:14<br/>
     * 机能概要:默认提供的模糊查询对中文来说,没有任何用
     * @throws Exception
     */
    public  static void getByFuzzy() throws Exception{
        System.out.println("-------------------------模糊查询---------------");
        FuzzyQuery query = new FuzzyQuery(new Term("username","zhangsan"));
        excQuery(query);
    }
 
    /**
     * 创建用户:狂飙的yellowcong<br/>
     * 创建日期:2017年12月3日<br/>
     * 创建时间:下午12:01:55<br/>
     * 机能概要:查询Query 将需要查询的条件传递进来
     * @param query
     */
    public static void excQuery(Query query){
        //查询
        IndexReader reader  = null;
        try {
            reader = getIndexReader();
 
            //获取查询数据
            IndexSearcher searcher = new IndexSearcher(reader);
 
            //检索数据
            TopDocs topDocs = searcher.search(query, 100);
            for(ScoreDoc scoreDoc : topDocs.scoreDocs){
                //湖区偶
                Document doc = reader.document(scoreDoc.doc);
                System.out.println(doc.get("id")+":"+doc.get("username")+":"+doc.get("email"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            coloseReader(reader);
        }
    }
    /**
     * 创建用户:狂飙的yellowcong<br/>
     * 创建日期:2017年12月3日<br/>
     * 创建时间:上午11:52:52<br/>
     * 机能概要:关闭IndexReader
     * @param reader
     */
    private static void coloseReader(IndexReader reader) {
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    static {
        psgList = new ArrayList<Passage>();
 
        // 产生一堆数据
        psgList.add(new Passage(1, "yellowcong" ,
                "717350389@qq.com", "逗比", 23 , "I LOVE YOU ", new Date()));
 
        psgList.add(new Passage(2, "张三" ,
                "zhashang@qq.com", "逗比", 23, "三炮", new Date()));
        psgList.add(new Passage(3, "李四" ,
                "lisi@neusoft.com", "逗比", 23, "三炮", new Date()));
        psgList.add(new Passage(4, "王五" ,
                "wangwu@aliyun.com", "逗比", 23, "三炮", new Date()));
        psgList.add(new Passage(5, "赵六" ,
                "zhaoliu@baidu.com", "逗比", 23, "三炮", new Date()));
        System.out.println("-------------------------添加的数据----------------------");
        for(Passage psg:psgList){
            System.out.println(psg.getId()+":"+psg.getUsername()+":"+psg.getEmail()+":"+psg.getContent());
        }
    }
 
    /**
     * 创建用户:狂飙的yellowcong<br/>
     * 创建日期:2017年12月2日<br/>
     * 创建时间:下午5:43:57<br/>
     * 机能概要:获取IndexWriter 同一时间 ,只能打开一个 IndexWriter,独占写锁 。内建线程安全机制。
     *
     * @return
     * @throws Exception
     */
    @SuppressWarnings("static-access")
    public static IndexWriter getIndexWriter() throws Exception {
        // 创建IdnexWriter
        String path = getIndexPath();
        FSDirectory fs = FSDirectory.open(new File(path));
        // 判断资源是否占用
        if (writer == null || !writer.isLocked(fs)) {
            synchronized (Demo3.class) {
                if (writer == null || !writer.isLocked(fs)) {
                    // 创建writer对象
                    writer = new IndexWriter(fs,
                            new IndexWriterConfig(Version.LUCENE_45, new StandardAnalyzer(Version.LUCENE_45)));
                }
            }
        }
        return writer;
    }
 
    /**
     * 创建用户:狂飙的yellowcong<br/>
     * 创建日期:2017年12月2日<br/>
     * 创建时间:下午5:46:36<br/>
     * 机能概要:获取到IndexReader 任意多个IndexReaders可同时打开,可以跨JVM。
     *
     * @return
     * @throws Exception
     */
    public static IndexReader getIndexReader() throws Exception {
        // 创建IdnexWriter
        String path = getIndexPath();
        FSDirectory fs = FSDirectory.open(new File(path));
        // 获取到读
        return IndexReader.open(fs);
    }
 
 
    /**
     * 创建用户:狂飙的yellowcong<br/>
     * 创建日期:2017年12月2日<br/>
     * 创建时间:下午7:57:04<br/>
     * 机能概要:删除所有的索引
     */
    public static void deleteAll() {
        IndexWriter writer = null;
        try {
            // 获取IndexWriter
            writer = getIndexWriter();
 
            // 删除所有的数据
            writer.deleteAll();
 
            int cnt = writer.numDocs();
            System.out.println("索引条数\t" + cnt);
 
            // 提交事物
            writer.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            coloseWriter(writer);
        }
    }
 
    /**
     * 创建用户:狂飙的yellowcong<br/>
     * 创建日期:2017年12月2日<br/>
     * 创建时间:下午5:37:22<br/>
     * 机能概要:获取索引目录
     *
     * @return 目录
     */
    private static String getIndexPath() {
        // 获取索引的目录
        String path = Demo3.class.getClassLoader().getResource("index").getPath();
 
        // 不存在就创建目录
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        return path;
    }
 
    /**
     * 创建用户:狂飙的yellowcong<br/>
     * 创建日期:2017年12月2日<br/>
     * 创建时间:下午8:24:16<br/>
     * 机能概要:关闭IndexWriter
     */
    private static void coloseWriter(IndexWriter writer) {
        try {
            if (writer != null) {
                writer.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 创建用户:狂飙的yellowcong<br/>
     * 创建日期:2017年12月2日<br/>
     * 创建时间:下午8:26:15<br/>
     * 机能概要:关闭IndexReader
     *
     * @param reader
     */
    public static void closerReader(IndexReader reader) {
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 创建用户:狂飙的yellowcong<br/>
     * 创建日期:2017年12月2日<br/>
     * 创建时间:下午8:10:01<br/>
     * 机能概要: 查询数据
     *
     * @param key
     *            查询范围
     * @param val
     *            值
     */
    public static void search(String key, Object val) {
        IndexReader reader = null;
        try {
            reader = getIndexReader();
 
            IndexSearcher searcher = new IndexSearcher(reader);
 
            // 精确查询
            Query query = null;
 
            // 定义查询条件
            if (val instanceof Integer) {
                // 后面的两个true 表示的是 是否包含 上下的数据
                query = NumericRangeQuery.newIntRange(key, Integer.parseInt(val.toString()),
                        Integer.parseInt(val.toString()), true, true);
            } else {
                query = new TermQuery(new Term(key, val.toString()));
            }
            // QueryParser paraser = new QueryParser(Version.LUCENE_45, key, new
            // StandardAnalyzer(Version.LUCENE_45));
            // Query query = paraser.parse(val);
 
            // 获取查询到的Docuemnt
            TopDocs topDocs = searcher.search(query, 500);
            // 总共命中的条数
            System.out.println(topDocs.totalHits);
            for (ScoreDoc score : topDocs.scoreDocs) {
                //
                Document doc = searcher.doc(score.doc);
 
                // 查询到的结果
                String username = doc.get("username");
                System.out.println(username);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closerReader(reader);
        }
    }
 
    /**
     * 创建用户:狂飙的yellowcong<br/>
     * 创建日期:2017年12月2日<br/>
     * 创建时间:下午6:03:33<br/>
     * 机能概要:建立索引
     */
    public static void index() {
        IndexWriter writer = null;
        try {
            // 1、获取IndexWriter
            writer = getIndexWriter();
 
            // 2、建立索引
            for (Passage psg : psgList) {
                Document doc = new Document();
 
                // IntField 不能直接检索到,需要结合
                doc.add(new IntField("id", psg.getId(), Field.Store.YES));
 
                // 用户String类型的字段的存储,StringField是只索引不分词
                doc.add(new TextField("username", psg.getUsername(), Field.Store.YES));
 
                // 主要对int类型的字段进行存储,需要注意的是如果需要对InfField进行排序使用SortField.Type.INT来比较,如果进范围查询或过滤,需要采用NumericRangeQuery.newIntRange()
                doc.add(new IntField("age", psg.getAge(), Field.Store.YES));
 
                // 对String类型的字段进行存储,TextField和StringField的不同是TextField既索引又分词
                doc.add(new TextField("content", psg.getContent(), Field.Store.NO));
 
                doc.add(new StringField("keyword", psg.getKeyword(), Field.Store.YES));
 
                doc.add(new StringField("email", psg.getEmail(), Field.Store.YES));
 
                // 日期数据添加索引
                doc.add(new LongField("addDate", psg.getAddDate().getTime(), Field.Store.YES));
 
                // 3、添加文档
                writer.addDocument(doc);
            }
 
            // 索引条数
            int cnt = writer.numDocs();
            System.out.println("索引条数\t" + cnt);
 
            // 提交事物
            writer.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            coloseWriter(writer);
        }
    }
 
    static class Passage {
        private int id;
        private String username;
        private String email;
        private String keyword;
        private int age;
        // 这个模拟的是文章
        private String content;
        private Date addDate;
 
        public Passage(int id, String username, String email, String keyword, int age, String content, Date addDate) {
            super();
            this.id = id;
            this.username = username;
            this.email = email;
            this.keyword = keyword;
            this.age = age;
            this.content = content;
            this.addDate = addDate;
        }
 
        public int getId() {
            return id;
        }
 
        public void setId(int id) {
            this.id = id;
        }
 
        public String getUsername() {
            return username;
        }
 
        public void setUsername(String username) {
            this.username = username;
        }
 
        public String getEmail() {
            return email;
        }
 
        public void setEmail(String email) {
            this.email = email;
        }
 
        public String getKeyword() {
            return keyword;
        }
 
        public void setKeyword(String keyword) {
            this.keyword = keyword;
        }
 
        public int getAge() {
            return age;
        }
 
        public void setAge(int age) {
            this.age = age;
        }
 
        public String getContent() {
            return content;
        }
 
        public void setContent(String content) {
            this.content = content;
        }
 
        public Date getAddDate() {
            return addDate;
        }
 
        public void setAddDate(Date addDate) {
            this.addDate = addDate;
        }
    }
}

  

posted on   范兵  阅读(5839)  评论(0编辑  收藏  举报

编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示