Example usage for org.apache.lucene.document Document get

List of usage examples for org.apache.lucene.document Document get

Introduction

In this page you can find the example usage for org.apache.lucene.document Document get.

Prototype

public final String get(String name) 

Source Link

Document

Returns the string value of the field with the given name if any exist in this document, or null.

Usage

From source file:GUIFrame.java

public int SearchResults(PorterStemAnalyzer Analyzer, Directory Index, String userInput,
        DefaultListModel DocList) throws ParseException, IOException {
    // The query//ww w  .java 2 s.c  o  m
    userInput = userInput.replace("\"", "");
    Query q = new QueryParser(Version.LATEST, "summary", Analyzer).parse(userInput);

    // The search
    int hitsPerPage = 20; // return 20 top documents
    IndexReader indoReader = DirectoryReader.open(Index);
    IndexSearcher indoSearcher = new IndexSearcher(indoReader);
    TopScoreDocCollector docCollector = TopScoreDocCollector.create(hitsPerPage, true);
    indoSearcher.search(q, docCollector);
    ScoreDoc[] hits = docCollector.topDocs().scoreDocs;

    // Copy results to list models
    for (int i = 0; i < hits.length; ++i) {
        int docId = hits[i].doc;
        Document d = indoSearcher.doc(docId);
        DocList.addElement(d.get("docID"));
        SumListModel.addElement(d.get("summary"));
    }

    GetTerms(Index, Analyzer, "summary", userInput);

    return hits.length;
}

From source file:SearchFiles.java

License:Apache License

/**
 * This demonstrates a typical paging search scenario, where the search engine presents 
 * pages of size n to the user. The user can then go to the next page if interested in
 * the next hits.//from  w ww .ja v  a  2s.  co  m
 * 
 * When the query is executed for the first time, then only enough results are collected
 * to fill 5 result pages. If the user wants to page beyond this limit, then the query
 * is executed another time and all hits are collected.
 * 
 */
public static void doPagingSearch(BufferedReader in, IndexSearcher searcher, Query query, int hitsPerPage,
        boolean raw, boolean interactive) throws IOException {

    // Collect enough docs to show 5 pages
    TopDocs results = searcher.search(query, 5 * hitsPerPage);
    ScoreDoc[] hits = results.scoreDocs;

    int numTotalHits = results.totalHits;
    System.out.println(numTotalHits + " total matching documents");

    int start = 0;
    int end = Math.min(numTotalHits, hitsPerPage);

    while (true) {
        if (end > hits.length) {
            System.out.println("Only results 1 - " + hits.length + " of " + numTotalHits
                    + " total matching documents collected.");
            System.out.println("Collect more (y/n) ?");
            String line = in.readLine();
            if (line.length() == 0 || line.charAt(0) == 'n') {
                break;
            }

            hits = searcher.search(query, numTotalHits).scoreDocs;
        }

        end = Math.min(hits.length, start + hitsPerPage);

        for (int i = start; i < end; i++) {
            if (raw) { // output raw format
                System.out.println("doc=" + hits[i].doc + " score=" + hits[i].score);
                continue;
            }

            Document doc = searcher.doc(hits[i].doc);
            String path = doc.get("path");
            if (path != null) {
                String title = doc.get("title");
                if (title != null && !title.equals("")) {
                    System.out.println((i + 1) + ". " + doc.get("title"));
                    System.out.println("       " + path);
                } else {
                    System.out.println((i + 1) + ". null");
                    System.out.println("       " + path);
                }
            } else {
                System.out.println((i + 1) + ". " + "No path for this document");
            }

        }

        if (!interactive || end == 0) {
            break;
        }

        if (numTotalHits >= end) {
            boolean quit = false;
            while (true) {
                System.out.print("Press ");
                if (start - hitsPerPage >= 0) {
                    System.out.print("(p)revious page, ");
                }
                if (start + hitsPerPage < numTotalHits) {
                    System.out.print("(n)ext page, ");
                }
                System.out.println("(q)uit or enter number to jump to a page.");

                String line = in.readLine();
                if (line.length() == 0 || line.charAt(0) == 'q') {
                    quit = true;
                    break;
                }
                if (line.charAt(0) == 'p') {
                    start = Math.max(0, start - hitsPerPage);
                    break;
                } else if (line.charAt(0) == 'n') {
                    if (start + hitsPerPage < numTotalHits) {
                        start += hitsPerPage;
                    }
                    break;
                } else {
                    int page = Integer.parseInt(line);
                    if ((page - 1) * hitsPerPage < numTotalHits) {
                        start = (page - 1) * hitsPerPage;
                        break;
                    } else {
                        System.out.println("No such page");
                    }
                }
            }
            if (quit)
                break;
            end = Math.min(numTotalHits, start + hitsPerPage);
        }
    }
}

From source file:MyServlet.java

private void gotoSearch(PrintWriter out, HttpServletRequest request, HttpServletResponse response) {
    try {/* w w  w.  jav a2 s. c o  m*/
        //   Text to search
        String querystr = request.getParameter("keyword");

        log.addHistory(querystr);

        //   The \"title\" arg specifies the default field to use when no field is explicitly specified in the query
        Query q = new QueryParser("Classes", analyzer).parse(querystr);

        // Searching code
        int hitsPerPage = 10;
        IndexReader reader = DirectoryReader.open(index);
        IndexSearcher searcher = new IndexSearcher(reader);
        TopScoreDocCollector collector = TopScoreDocCollector.create(hitsPerPage);
        searcher.search(q, collector);
        ScoreDoc[] hits = collector.topDocs().scoreDocs;

        //   Code to display the results of search
        //out.println("Found " + hits.length + " Classes Matching your Requirement");
        courseList = new ArrayList();
        for (int i = 0; i < hits.length; ++i) {
            int docId = hits[i].doc;
            Document d = searcher.doc(docId);
            Course course = new Course(d.get("Number"), d.get("Classes"), d.get("Time"), d.get("Department"));
            //out.println((i + 1) + ". " +  d.get("Number")+ d.get("Classes") );
            courseList.add(course);
        }
        request.setAttribute("course", courseList);
        RequestDispatcher de = request.getRequestDispatcher("/table.jsp");
        de.forward(request, response);

        // reader can only be closed when there is no need to access the documents any more
        reader.close();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

From source file:SearcherTest.java

/**
 * ?/*from w ww.  j a va2 s  .  c o  m*/
 * ???TermQuery
 * TermQuery??QueryTermQuery???????
 * ??????TermQuery??
 * Lucene??????????/
 * ??????????
 *
 * @throws Exception
 */
@Test
public void testTermQuery() throws Exception {
    String searchField = "contents";
    String q = "xxxxxxxxx$";
    Term t = new Term(searchField, q);
    Query query = new TermQuery(t);
    TopDocs hits = is.search(query, 10);
    System.out.println("? '" + q + "'" + hits.totalHits + "");
    for (ScoreDoc scoreDoc : hits.scoreDocs) {
        Document doc = is.doc(scoreDoc.doc);
        System.out.println(doc.get("fullPath"));
    }
}

From source file:SearcherTest.java

/**
 * ???BooleanQuery/*from   w ww  .j ava  2s .c om*/
 * BooleanQuery???Query
 * ?Query???Query
 * ?BooleanQuery??
 * BooleanQuery?????API??
 * ?BooleanQuery????API?
 *
 * @throws Exception
 */
@Test
public void testBooleanQuery() throws Exception {
    String searchField = "contents";
    String q1 = "xxxxxxxxx";
    String q2 = "oooooooooooooooo";
    Query query1 = new TermQuery(new Term(searchField, q1));
    Query query2 = new TermQuery(new Term(searchField, q2));
    BooleanQuery.Builder builder = new BooleanQuery.Builder();
    //  1MUSTMUST???
    //  2MUSTMUST_NOT??MUST_NOT??
    // 3SHOULDMUST_NOT?MUSTMUST_NOT
    // 4SHOULDMUSTMUST??,SHOULD???
    // 5SHOULDSHOULD???
    // 6MUST_NOTMUST_NOT?
    builder.add(query1, BooleanClause.Occur.MUST);
    builder.add(query2, BooleanClause.Occur.MUST);
    BooleanQuery booleanQuery = builder.build();
    TopDocs hits = is.search(booleanQuery, 10);
    System.out.println("? " + q1 + "And" + q2 + "" + hits.totalHits + "");
    for (ScoreDoc scoreDoc : hits.scoreDocs) {
        Document doc = is.doc(scoreDoc.doc);
        System.out.println(doc.get("fullPath"));
    }
}

From source file:SearcherTest.java

/**
 * TermRangeQuery //from w  w  w  . ja v a  2s .  c om
 * TermRangeQuery???
 * ?ASC??ASC?
 * ?ASC??
 * ASC??TermRangeQuery
 * ?NumericRangeQuery
 * ?????
 *
 * @throws Exception
 */
@Test
public void testTermRangeQuery() throws Exception {
    String searchField = "contents";
    String q = "1000001----1000002";
    String lowerTermString = "1000001";
    String upperTermString = "1000003";
    /**
     * field  
     * lowerterm -
     *upperterm -?
     *includelower -lowerterm
     *includeupper -upperterm
     *https://yq.aliyun.com/articles/45353
     */
    Query query = new TermRangeQuery(searchField, new BytesRef(lowerTermString), new BytesRef(upperTermString),
            true, true);
    TopDocs hits = is.search(query, 10);
    System.out.println("? '" + q + "'" + hits.totalHits + "");
    for (ScoreDoc scoreDoc : hits.scoreDocs) {
        Document doc = is.doc(scoreDoc.doc);
        System.out.println(doc.get("fullPath"));
    }
}

From source file:SearcherTest.java

/**
 * PrefixQuery  PrefixQuery?xxx%/*from ww w .ja  v a  2s. c o  m*/
 *
 * @throws Exception
 */
@Test
public void testPrefixQuery() throws Exception {
    String searchField = "contents";
    String q = "1license";
    Term t = new Term(searchField, q);
    Query query = new PrefixQuery(t);
    TopDocs hits = is.search(query, 10);
    System.out.println("? '" + q + "'" + hits.totalHits + "");

    for (ScoreDoc scoreDoc : hits.scoreDocs) {
        Document doc = is.doc(scoreDoc.doc);
        System.out.println(doc.get("fullPath"));
    }
}

From source file:SearcherTest.java

/**
 * PhraseQuery?big car?//w  w w.  j a v a  2  s  .  c  om
 * ?document?"big car"
 * document???????big black car?
 * ????slop
 * slopslop???
 *
 * @throws Exception
 */
@Test
public void testPhraseQuery() throws Exception {
    String searchField = "contents";
    String q1 = "xxxx";
    String q2 = "bbb";
    Term t1 = new Term(searchField, q1);
    Term t2 = new Term(searchField, q2);
    PhraseQuery.Builder builder = new PhraseQuery.Builder();
    builder.add(t1);
    builder.add(t2);
    builder.setSlop(0);
    PhraseQuery query = builder.build();
    TopDocs hits = is.search(query, 10);
    System.out.println("? '" + q1 + q2 + "" + "" + hits.totalHits
            + "");

    for (ScoreDoc scoreDoc : hits.scoreDocs) {
        Document doc = is.doc(scoreDoc.doc);
        System.out.println(doc.get("fullPath"));
    }
}

From source file:SearcherTest.java

/**
 * ??FuzzyQuery//from  ww  w  .  j a v a 2 s .  c  om
 * FuzzyQuery????
 *
 * @throws Exception
 */
@Test
public void testFuzzyQuery() throws Exception {
    String searchField = "contents";
    String q = "ljlxx";
    Term t = new Term(searchField, q);
    Query query = new FuzzyQuery(t);
    TopDocs hits = is.search(query, 10);
    System.out.println("? '" + q + "'" + hits.totalHits + "");

    for (ScoreDoc scoreDoc : hits.scoreDocs) {
        Document doc = is.doc(scoreDoc.doc);
        System.out.println(doc.get("fullPath"));
    }
}

From source file:SearcherTest.java

/**
 * ??WildcardQuery/*from w ww.ja  v  a 2 s .c  o m*/
 * Lucene???WildcardQuery
 * ???1*?0
 *
 * @throws Exception
 */
@Test
public void testWildcardQuery() throws Exception {
    String searchField = "contents";
    String q = "bb??qq";
    Term t = new Term(searchField, q);
    Query query = new WildcardQuery(t);
    TopDocs hits = is.search(query, 10);
    System.out.println("? '" + q + "'" + hits.totalHits + "");

    for (ScoreDoc scoreDoc : hits.scoreDocs) {
        Document doc = is.doc(scoreDoc.doc);
        System.out.println(doc.get("fullPath"));
    }
}