其中
數(shù)字范圍查詢:索引時(shí)字段保存為
new NumericField(name, Field.Store.YES(NO), true(false).setIntValue( num );
Query numericRangeQuery = NumericRangeQuery.newIntRange("size", 20, 150, true, true);
時(shí)間范圍查詢,,其實(shí)就是數(shù)字范圍查詢,, 因?yàn)槎贾繢ate是根據(jù)一個(gè)long 型變量構(gòu)造出來(lái)的
所以用法同上,, 只不過(guò)需要對(duì)傳入的日期格式轉(zhuǎn)換成long
- public class QueryTest {
- @Test
- public void testTermQuery() throws Exception {
-
- Term term = new Term("size", "53");
- TermQuery termQuery = new TermQuery(term);
- doSearch(termQuery);
- }
-
- @Test
- public void testRangeQuery() throws Exception {
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Query numericRangeQuery = NumericRangeQuery.newLongRange("size", 20L, 150L, true, true);
- doSearch(numericRangeQuery);
- }
-
- @Test
- public void testPrefixQuery() throws Exception {
-
- Term term = new Term("name", "j");
- PrefixQuery prefixQuery = new PrefixQuery(term);
- doSearch(prefixQuery);
- }
-
- @Test
- public void testBooleanQuery() throws Exception {
-
-
- long min_time = 1334485513724L - 1000L;
- long max_time = 1334485513724L + 1000L;
- Query num_range_query = NumericRangeQuery.newLongRange("date", min_time, max_time, true, true);
-
-
- Query termQuery = new TermQuery(new Term("name", "test"));
-
-
- Query prefixQuery = new PrefixQuery(new Term("name", "j"));
-
- BooleanQuery booleanQuery = new BooleanQuery();
- booleanQuery.add(num_range_query, BooleanClause.Occur.MUST);
- booleanQuery.add(termQuery, BooleanClause.Occur.MUST_NOT);
- booleanQuery.add(prefixQuery, BooleanClause.Occur.SHOULD);
- doSearch(booleanQuery);
- }
- @Test
- public void testPhraseQuery() throws Exception {
- PhraseQuery phraseQuery = new PhraseQuery();
-
-
-
- String[] strs = {"quick", "brown", "jumped", "lazy"};
-
-
-
-
- phraseQuery.setSlop(3);
- for(String s: strs){
- phraseQuery.add(new Term("content", s));
- }
- doSearch(phraseQuery);
- }
-
-
-
-
-
- @Test
- public void testWildcardQuery() throws Exception {
-
- Term term = new Term("content", "全*大");
- Query wildcardQuery = new WildcardQuery(new Term("name", "j*a"));
- doSearch(wildcardQuery);
- }
-
- /**
- * 模糊查詢
- * @throws Exception
- */
- @Test
- public void testFuzzyQuery() throws Exception {
- Term term = new Term("name", "jeav");
- Query fuzzyQuery = new FuzzyQuery(term);
- doSearch(fuzzyQuery);
- }
-
- private void doSearch(Query query) throws Exception{
- Directory dir = FSDirectory.open(new File("E:/lucene/index"));
- IndexReader reader = IndexReader.open(dir);
- IndexSearcher searcher = new IndexSearcher(reader);
- TopDocs hits = searcher.search(query, 100);
- System.out.println("共找到" + hits.totalHits + "條記錄");
- ScoreDoc[] docs = hits.scoreDocs;
- for(int i = 0; i < docs.length; i++){
- int docId = docs[i].doc;
- Document doc = searcher.doc(docId);
- System.out.println("name: " + doc.get("name"));
- System.out.println("size: " + doc.get("size"));
- System.out.println("content: " + doc.get("content"));
- }
- searcher.close();
- }
- }