Example usage for org.apache.lucene.search IndexSearcher doc

List of usage examples for org.apache.lucene.search IndexSearcher doc

Introduction

In this page you can find the example usage for org.apache.lucene.search IndexSearcher doc.

Prototype

public Document doc(int docID) throws IOException 

Source Link

Document

Sugar for .getIndexReader().document(docID)

Usage

From source file:GUIFrame.java

public int SearchResults(PorterStemAnalyzer Analyzer, Directory Index, String userInput,
        DefaultListModel DocList) throws ParseException, IOException {
    // The query//from  www .ja  v a2 s.co  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  w  w . j  av a2 s.c  o  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 {/*from  w ww  .  java 2s.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:IrqaQuery.java

License:Apache License

public static List<Document> query(String index, String stoppath, String question, int numResult, String sim)
        throws Exception {
    IndexReader reader = DirectoryReader.open(FSDirectory.open(Paths.get(index)));
    IndexSearcher searcher = new IndexSearcher(reader);

    Analyzer analyzer = new EnglishAnalyzer(StopFilter.makeStopSet(mygetStopwords(stoppath)));

    if (sim.equals("TFIDF"))
        searcher.setSimilarity(new ClassicSimilarity());
    else if (sim.equals("BM25"))
        searcher.setSimilarity(new BM25Similarity());
    else/*from   ww w  . ja va 2  s.  com*/
        searcher.setSimilarity(new BM25Similarity());

    String field = "contents";
    QueryParser parser = new QueryParser(field, analyzer);
    Query query = parser.parse(parser.escape(question));

    TopDocs results = searcher.search(query, numResult);
    ScoreDoc[] hits = results.scoreDocs;
    List<Document> docs = new ArrayList<Document>();

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

    int end = Math.min(numTotalHits, numResult);

    String searchResult = "";
    //        System.out.println("Only results 1 - " + hits.length);

    for (int i = 0; i < end; i++) {
        Document doc = searcher.doc(hits[i].doc);
        docs.add(doc);
    }

    return docs;
}

From source file:Get_Top_Documents_Based_on_Lucene.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 w w.j  a v  a  2s . com*/
 * 
 * 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, Writer writer, IndexSearcher searcher, Query query,
        int hitsPerPage, boolean raw, boolean interactive) throws IOException {

    // Collect enough docs to show 5 pages
    TopDocs results = searcher.search(query, hitsPerPage);
    ScoreDoc[] hits = results.scoreDocs;
    System.out.println("hits.length: " + Integer.toString(hits.length));
    for (int i = 0; i < hits.length; i++) {
        Document doc = searcher.doc(hits[i].doc);
        String path = doc.get("path");
        writer.write(path + ",");
        //System.out.println("Path: " + path);
        //String title = doc.get("title");
        //System.out.println("Title: " + title);
    } //for
    writer.write("\n");
    /*
    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) {
          System.out.println((i+1) + ". " + path);
          String title = doc.get("title");
          if (title != null) {
    System.out.println("   Title: " + doc.get("title"));
          }
        } 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:QueryLuceneIndex.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.//w  w  w  . j av  a 2 s.  c om
 * 
 * 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 title = doc.get("title");
            if (title != null) {
                System.out.println((i + 1) + ". " + title);

            } else {
                System.out.println((i + 1) + ". " + "No title 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:SearchFiles11.java

License:Apache License

/** Simple command-line based search demo. */
public static void main(String[] args) throws Exception {
    String usage = "Usage:\tjava org.apache.lucene.demo.SearchFiles [-index dir] [-field f] [-repeat n] [-queries file] [-query string] [-raw] [-paging hitsPerPage]\n\nSee http://lucene.apache.org/core/4_1_0/demo/ for details.";
    if (args.length > 0 && ("-h".equals(args[0]) || "-help".equals(args[0]))) {
        System.out.println(usage);
        System.exit(0);/*from   w ww . j a  v a2  s .  co m*/
    }

    String index = "index";
    String field = "contents";
    String queries = null;
    int repeat = 0;
    boolean raw = false;
    String queryString = null;
    int hitsPerPage = 10;

    for (int i = 0; i < args.length; i++) {
        if ("-index".equals(args[i])) {
            index = args[i + 1];
            i++;
        } else if ("-field".equals(args[i])) {
            field = args[i + 1];
            i++;
        } else if ("-queries".equals(args[i])) {
            queries = args[i + 1];
            i++;
        } else if ("-query".equals(args[i])) {
            queryString = args[i + 1];
            i++;
        } else if ("-repeat".equals(args[i])) {
            repeat = Integer.parseInt(args[i + 1]);
            i++;
        } else if ("-raw".equals(args[i])) {
            raw = true;
        } else if ("-paging".equals(args[i])) {
            hitsPerPage = Integer.parseInt(args[i + 1]);
            if (hitsPerPage <= 0) {
                System.err.println("There must be at least 1 hit per page.");
                System.exit(1);
            }
            i++;
        }
    }

    IndexReader reader = DirectoryReader.open(FSDirectory.open(Paths.get(index)));
    IndexSearcher searcher = new IndexSearcher(reader);
    Analyzer analyzer = new StandardAnalyzer();

    StandardQueryParser queryParserHelper = new StandardQueryParser();

    Query query = queryParserHelper.parse(
            "Physical OR tests OR for OR shoulder OR impingements OR and OR local OR lesions OR of OR bursa, OR tendon OR labrum OR that OR may OR accompany OR impingement",
            field);

    TopDocs results = searcher.search(query, 100);
    Date end = new Date();
    ScoreDoc[] hits = results.scoreDocs;
    int numTotalHits = results.totalHits;

    String FILENAME = "/home/devil/research/CLEF/ehealth/task2/dataset/pubmed11.res";

    int i = 1;
    try (BufferedWriter bw = new BufferedWriter(new FileWriter(FILENAME))) {
        String content = "";
        for (ScoreDoc h : hits) {
            Document doc = searcher.doc(h.doc);
            String path = doc.get("path");
            String[] path_words = path.split("/");
            System.out.println(path_words[path_words.length - 1] + " score=" + h.score);

            content = "CD007427 " + "NF " + path_words[path_words.length - 1] + " " + i++ + " " + h.score
                    + " pubmed\n";

            bw.write(content);
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
    //doPagingSearch(in, searcher, bQuery.build(), hitsPerPage, raw, queries == null && queryString == null);
    reader.close();

}

From source file:SearchFiles11.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 w  w  .  j  a v  a  2 s  . com
 * 
 * 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) {
                System.out.println((i + 1) + ". " + path);
                String title = doc.get("title");
                if (title != null) {
                    System.out.println("   Title: " + doc.get("title"));
                }
            } 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:CFX_GoatSearch.java

License:Open Source License

/**
 * Classes that implement this interface can be specified in the CLASS attribute of the Java CFX tag. For example, in a class MyCustomTag, which implements this interface, the following CFML code calls the MyCustomTag.processRequest method.
 *
 * @param request// w w  w  .  j  a v a  2  s  . co  m
 * @param response
 * @throws Exception
 */
public void processRequest(Request request, Response response) throws Exception {

    Date startTime = new Date();
    String indexPath = null;
    String queryName = null;
    String searchString = null;
    String sortField = null;
    String sortDirection = null;
    int hitsPerPage = 0;
    int pageNumber = 0;
    Vector errors = new Vector();

    if (request.attributeExists("INDEXPATH")) {
        indexPath = request.getAttribute("INDEXPATH");
    } else {
        errors.add("The cfx_lucene tag requires an attribute called 'INDEXPATH'.");
    }

    if (request.attributeExists("HITSPERPAGE")) {
        hitsPerPage = request.getIntAttribute("HITSPERPAGE");
    }

    if (request.attributeExists("PAGENUMBER")) {
        pageNumber = request.getIntAttribute("PAGENUMBER");
    }

    if (request.attributeExists("QUERYNAME")) {
        queryName = request.getAttribute("QUERYNAME");
    } else {
        errors.add("The cfx_lucene tag requires an attribute called 'QUERYNAME'.");
    }

    if (request.attributeExists("SEARCHSTRING")) {
        searchString = request.getAttribute("SEARCHSTRING");
    } else {
        errors.add("The cfx_lucene tag requires an attribute called 'SEARCHSTRING'.");
    }

    //Sorting
    if (request.attributeExists("SORTFIELD")) {
        sortField = request.getAttribute("SORTFIELD");
    }

    if (request.attributeExists("SORTDIRECTION")) {
        sortDirection = request.getAttribute("SORTDIRECTION");
    }

    //Errors
    if (!errors.isEmpty()) {
        response.write("<h2 style=\"color: #FF0000\">CFX Goat Error:</h2>");
        for (int i = 0; i < errors.size(); i++) {
            response.write("<p>Error: " + errors.get(i) + "</p>\n");
        }
        //return;
    } else {

        try {

            IndexReader reader = IndexReader.open(indexPath);
            IndexSearcher searcher = new IndexSearcher(indexPath);
            if (searcher == null) {
                errors.add("Unable to open index");
            }

            XMLReader readerXML = new XMLReader(); //XML Reader Class
            String configFile = ConfigFiles.getSchemaFile(indexPath);
            String[] indexTypeArray = new String[Integer.parseInt(readerXML.getTotalNodes(configFile))];
            String[] columnNamesArray = new String[Integer.parseInt(readerXML.getTotalNodes(configFile))]; //Add Column Names
            int totalNodes = columnNamesArray.length;
            String nodeName = "";
            //Sort .:.  Index Type must be PrimaryKey,Keyword,Date
            Sort sortby = new Sort();
            if (sortField != null)
                sortField.trim().toLowerCase(); //Change Field TO LowerCase

            Analyzer analyzer = new StandardAnalyzer();
            QueryParser parser = new MultiFieldQueryParser(columnNamesArray, analyzer);
            Query query = parser.parse(searchString);
            if (query == null) {
                errors.add("Unable to build Query");
            }
            //Build Query Here             
            //Get Column Names
            for (int i = 0; i < totalNodes; i++) {
                columnNamesArray[i] = readerXML.getNodeValueByFile(configFile, i, "columnname");
                indexTypeArray[i] = readerXML.getNodeValueByFile(configFile, i, "indextype");

                /* Make Sure Field Can Be Seached */
                if (columnNamesArray[i].equalsIgnoreCase(sortField)
                        && (indexTypeArray[i].equalsIgnoreCase("PrimaryKey")
                                || indexTypeArray[i].equalsIgnoreCase("Keyword")
                                || indexTypeArray[i].equalsIgnoreCase("Date"))) {
                    //Sort Ascending 
                    if (sortDirection != null && sortDirection.equalsIgnoreCase("desc")) {
                        System.out.println("desc");
                        sortby = new Sort(sortField, true);
                    } else if (sortDirection != null && sortDirection.equalsIgnoreCase("asc")) {
                        System.out.println("asc");
                        sortby = new Sort(sortField, false);
                    }

                }

            }

            if (hitsPerPage < 1)
                hitsPerPage = 1;
            int pageNum = pageNumber;
            int recordSet = (pageNum * hitsPerPage) + 100;

            TopFieldDocs resultDocs = searcher.search(query, null, recordSet, sortby);
            ScoreDoc[] hits = resultDocs.scoreDocs;
            int numTotalHits = resultDocs.totalHits;

            //Start
            int start = (pageNum - 1);
            if (start < 0)
                start = 0;

            if (pageNum > 1) {
                start = (pageNum * hitsPerPage) - hitsPerPage;
            }

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

            //Coldfusion Query
            com.allaire.cfx.Query goatQuery = response.addQuery(queryName, columnNamesArray);

            for (int i = start; i < end; i++) {
                int row = goatQuery.addRow(); //Add Row
                int docId = hits[i].doc;
                Document d = searcher.doc(docId);

                for (int x = 0; x < totalNodes; x++) {
                    nodeName = columnNamesArray[x];
                    goatQuery.setData(row, (x + 1), d.get(nodeName)); //Insert Values .:. Set Data starts with 1                  

                }
            }

            //reader.close();  
            searcher.close();
            Date endTime = new Date();

            //Set other Values
            response.setVariable("goat.totaltime", Long.toString(endTime.getTime() - startTime.getTime()));
            response.setVariable("goat.totalresults", Integer.toString(numTotalHits));
            response.setVariable("goat.totalpages", Integer.toString((numTotalHits / hitsPerPage)));
        }

        catch (Exception e) {
            errors.add("Failure caught a " + e.getClass() + " with message: " + e.getMessage());
        }
    }

    //Output Final Errors If Needed
    if (!errors.isEmpty()) {
        response.write("<h2 style=\"color: #FF0000\">CFX Goat Error:</h2>");
        for (int i = 0; i < errors.size(); i++) {
            response.write("<p>Error: " + errors.get(i) + "</p>\n");
        }
    }

}

From source file:ReadFiles.java

License:Apache License

public static Result doSearch(String path, DIRTYPE type, IndexReader ir) throws IOException {
    IndexReader reader;/*from   www. j  av  a  2  s.  c  o m*/
    Result r = new Result();
    long beginTs, endTs;

    if (ir != null)
        reader = ir;
    else {
        beginTs = System.currentTimeMillis();
        switch (type) {
        default:
        case MMAP:
            reader = DirectoryReader.open(MMapDirectory.open(new File(path)));
            break;
        case NIO:
            reader = DirectoryReader.open(NIOFSDirectory.open(new File(path)));
            break;
        case SIMPLE:
            reader = DirectoryReader.open(SimpleFSDirectory.open(new File(path)));
            break;
        }
        endTs = System.currentTimeMillis();
        r.initTs += endTs - beginTs;
        r.initTsNr += 1;
    }

    System.out.println("-----Search it------");

    IndexSearcher searcher = new IndexSearcher(reader);

    Query q = NumericRangeQuery.newIntRange("foo", new Integer("100000"), null, false, false);
    beginTs = System.currentTimeMillis();
    ScoreDoc[] hits = searcher.search(q, searcher.getIndexReader().maxDoc()).scoreDocs;
    endTs = System.currentTimeMillis();
    r.searchTs += endTs - beginTs;
    r.searchTsNr += hits.length;
    System.out.println("Hits -> " + hits.length);

    boolean isSeq = true;
    int lastid = 0;
    beginTs = System.currentTimeMillis();
    for (int i = 0; i < hits.length; i++) {
        if (hits[i].doc < lastid)
            isSeq = false;
        Document doc = searcher.doc(hits[i].doc);
        doc.get("foo");
        doc.get("bar");
        //System.out.println("Key: " + doc.get("foo") + ", Value: " + doc.get("bar"));
    }
    System.out.println("Search DocID is SEQ? " + isSeq);
    endTs = System.currentTimeMillis();
    r.fetchTs += endTs - beginTs;
    r.fetchTsNr += hits.length;

    if (ir == null) {
        beginTs = System.currentTimeMillis();
        reader.close();
        endTs = System.currentTimeMillis();
        r.closeTs += endTs - beginTs;
        r.closeTsNr += 1;
    }

    return r;
}