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

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

Introduction

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

Prototype

protected void search(List<LeafReaderContext> leaves, Weight weight, Collector collector) throws IOException 

Source Link

Document

Lower-level search API.

Usage

From source file:com.knowgate.lucene.BugSearcher.java

License:Open Source License

/**
 * Compose a Lucene query based on given parameters
 * @param sLuceneIndexPath String Base path for Lucene indexes excluding WorkArea and table name
 * @param sWorkArea String GUID of WorkArea to be searched, cannot be null
 * @param sProject String GUID f project to which bug belongs
 * @param sReportedBy String/*from   w w w. j  a  v  a2  s . co  m*/
 * @param sWrittenBy String
 * @param sTitle String
 * @param sFromDate String
 * @param sToDate String
 * @param sType String
 * @param sPriority String
 * @param sSeverity String
 * @param sStatus String
 * @param sText String
 * @param sComments String
 * @param iLimit int
 * @param oSortBy Comparator
 * @return BugRecord[]
 * @throws ParseException
 * @throws IOException
 * @throws NullPointerException
 */
public static BugRecord[] search(String sLuceneIndexPath, String sWorkArea, String sProjectGUID,
        String sReportedBy, String sWrittenBy, String sTitle, Date dtFromDate, Date dtToDate, String sType,
        String sPriority, String sSeverity, String sStatus, String sText, String sComments, int iLimit,
        Comparator oSortBy) throws ParseException, IOException, NullPointerException {

    if (null == sLuceneIndexPath)
        throw new NullPointerException("BugSearcher.search() luceindex parameter cannot be null");

    if (null == sWorkArea)
        throw new NullPointerException("BugSearcher.search() workarea parameter cannot be null");

    if (DebugFile.trace) {
        DebugFile.writeln("Begin BugSearcher.search(" + sLuceneIndexPath + "," + sWorkArea + "," + sProjectGUID
                + "," + sReportedBy + "," + sWrittenBy + "," + sTitle + "," + dtFromDate + "," + dtToDate + ","
                + sType + "," + sPriority + "," + sSeverity + "," + "," + sStatus + "," + sText
                + String.valueOf(iLimit) + ")");
        DebugFile.incIdent();
    }

    BugRecord[] aRetArr;

    BooleanQuery oQry = new BooleanQuery();

    oQry.add(new TermQuery(new Term("workarea", sWorkArea)), BooleanClause.Occur.MUST);

    if (null != sProjectGUID)
        if (sProjectGUID.length() > 0)
            oQry.add(new TermQuery(new Term("container", sProjectGUID)), BooleanClause.Occur.MUST);

    if (null != sWrittenBy)
        if (sWrittenBy.length() > 0)
            oQry.add(new TermQuery(new Term("writer", sWrittenBy)), BooleanClause.Occur.MUST);

    if (null != sReportedBy)
        if (sReportedBy.length() > 0)
            oQry.add(new TermQuery(new Term("author", sReportedBy)), BooleanClause.Occur.MUST);

    if (null != sTitle)
        if (sTitle.length() > 0)
            oQry.add(new TermQuery(new Term("title", sTitle)), BooleanClause.Occur.MUST);

    if (null != sType)
        if (sType.length() > 0)
            oQry.add(new TermQuery(new Term("type", sType)), BooleanClause.Occur.MUST);

    if (null != sStatus)
        if (sStatus.length() > 0)
            oQry.add(new TermQuery(new Term("status", sStatus)), BooleanClause.Occur.MUST);

    if (null != sPriority)
        if (sPriority.length() > 0)
            oQry.add(new TermQuery(new Term("priority", sPriority)), BooleanClause.Occur.MUST);

    if (null != sSeverity)
        if (sSeverity.length() > 0)
            oQry.add(new TermQuery(new Term("severity", sSeverity)), BooleanClause.Occur.MUST);

    if (dtFromDate != null && dtToDate != null)
        oQry.add(
                new TermRangeQuery("created", DateTools.dateToString(dtFromDate, DateTools.Resolution.DAY),
                        DateTools.dateToString(dtToDate, DateTools.Resolution.DAY), true, true),
                BooleanClause.Occur.MUST);
    else if (dtFromDate != null)
        oQry.add(new TermRangeQuery("created", DateTools.dateToString(dtFromDate, DateTools.Resolution.DAY),
                null, true, false), BooleanClause.Occur.MUST);
    else if (dtToDate != null)
        oQry.add(new TermRangeQuery("created", null, DateTools.dateToString(dtToDate, DateTools.Resolution.DAY),
                false, true), BooleanClause.Occur.MUST);
    if (null != sText)
        if (sText.length() > 0)
            oQry.add(new TermQuery(new Term("text", sText)), BooleanClause.Occur.SHOULD);

    if (null != sComments)
        if (sComments.length() > 0)
            oQry.add(new TermQuery(new Term("comments", sComments)), BooleanClause.Occur.SHOULD);

    String sSegments = Gadgets.chomp(sLuceneIndexPath, File.separator) + "k_bugs" + File.separator + sWorkArea;
    if (DebugFile.trace)
        DebugFile.writeln("new IndexSearcher(" + sSegments + ")");
    Directory oFsDir = Indexer.openDirectory(sSegments);
    IndexSearcher oSearch = new IndexSearcher(oFsDir);

    Document oDoc;

    TopDocs oTopSet = oSearch.search(oQry, null, iLimit > 0 ? iLimit : 2147483647);
    if (oTopSet.scoreDocs != null) {
        ScoreDoc[] oTopDoc = oTopSet.scoreDocs;
        int iDocCount = oTopDoc.length;
        aRetArr = new BugRecord[iDocCount];
        for (int d = 0; d < iDocCount; d++) {
            oDoc = oSearch.doc(oTopDoc[d].doc);
            aRetArr[d] = new BugRecord(oTopDoc[d].score, Integer.parseInt(oDoc.get("number")), oDoc.get("guid"),
                    oDoc.get("container"), oDoc.get("title"), oDoc.get("author"), oDoc.get("created"),
                    oDoc.get("type"), oDoc.get("status"), oDoc.get("priority"), oDoc.get("severity"),
                    oDoc.get("abstract"));
        } // next
    } else {
        aRetArr = null;
    }

    oSearch.close();
    oFsDir.close();

    if (oSortBy != null) {
        Arrays.sort(aRetArr, oSortBy);
    }

    if (DebugFile.trace) {
        DebugFile.decIdent();
        if (null == aRetArr)
            DebugFile.writeln("End BugSearcher.search() : no records found");
        else
            DebugFile.writeln("End BugSearcher.search() : " + String.valueOf(aRetArr.length));
    }
    return aRetArr;
}

From source file:com.knowgate.lucene.ContactSearcher.java

License:Open Source License

/**
 * Compose a Lucene query based on given parameters
 * @param sLuceneIndexPath String Base path for Lucene indexes excluding WorkArea and table name
 * @param sWorkArea String GUID of WorkArea to be searched, cannot be null
 * @param sProject String GUID f project to which bug belongs
 * @param sReportedBy String//w ww.j  a va  2  s.c o  m
 * @param sWrittenBy String
 * @param sTitle String
 * @param sFromDate String
 * @param sToDate String
 * @param sType String
 * @param sPriority String
 * @param sSeverity String
 * @param sStatus String
 * @param sText String
 * @param sComments String
 * @param iLimit int
 * @param oSortBy Comparator
 * @return BugRecord[]
 * @throws ParseException
 * @throws IOException
 * @throws NullPointerException
 */
public static ContactRecord[] search(Properties oProps, String sWorkArea, String values[],
        boolean obligatorio[]) throws ParseException, IOException, NullPointerException {

    if (null == oProps.getProperty("luceneindex"))
        throw new NullPointerException("ContactSearcher.search() luceindex parameter cannot be null");

    if (null == sWorkArea)
        throw new NullPointerException("ContactSearcher.search() workarea parameter cannot be null");

    if (DebugFile.trace) {
        DebugFile.writeln("Begin ContactSearcher.search(" + oProps.getProperty("luceneindex") + "," + sWorkArea
                + "," + String.valueOf(20) + ")");
        DebugFile.incIdent();
    }

    BooleanQuery oQry = new BooleanQuery();

    oQry.add(new TermQuery(new Term("workarea", sWorkArea)), BooleanClause.Occur.MUST);

    for (int i = 0; i < values.length; i++) {
        if (obligatorio[i]) {
            oQry.add(new TermQuery(new Term("value", values[i])), BooleanClause.Occur.MUST);
        } else {
            oQry.add(new TermQuery(new Term("value", values[i])), BooleanClause.Occur.SHOULD);
        }
    }

    String sSegments = Gadgets.chomp(oProps.getProperty("luceneindex"), File.separator) + "k_contacts"
            + File.separator + sWorkArea;
    if (DebugFile.trace)
        DebugFile.writeln("new IndexSearcher(" + sSegments + ")");

    File oDir = new File(sSegments);
    if (!oDir.exists()) {
        try {
            Indexer.rebuild(oProps, "k_contacts", sWorkArea);
        } catch (Exception e) {
            if (DebugFile.trace)
                DebugFile.writeln(e.getMessage());
        }
    }
    Directory oFsDir = Indexer.openDirectory(sSegments);
    IndexSearcher oSearch = new IndexSearcher(oFsDir);

    Document oDoc;

    ContactRecord aRetArr[] = null;

    TopDocs oTopSet = oSearch.search(oQry, null, 20);
    if (oTopSet.scoreDocs != null) {
        ScoreDoc[] oTopDoc = oTopSet.scoreDocs;
        int iDocCount = oTopDoc.length;
        aRetArr = new ContactRecord[iDocCount];
        for (int d = 0; d < iDocCount; d++) {
            oDoc = oSearch.doc(oTopDoc[d].doc);
            // String[] aAbstract = Gadgets.split(oSearch.doc(oTopDoc[d].doc).get("abstract"), '');
            aRetArr[d] = new ContactRecord(oTopDoc[d].score, oDoc.get("author"), oDoc.get("workarea"),
                    oDoc.get("guid"), oDoc.get("value"));
        } // next
    } else {
        aRetArr = null;
    }

    oSearch.close();
    oFsDir.close();

    if (DebugFile.trace) {
        DebugFile.decIdent();
        if (null == aRetArr)
            DebugFile.writeln("End ContactSearcher.search() : no records found");
        else
            DebugFile.writeln("End ContactSearcher.search() : " + String.valueOf(aRetArr.length));
    }
    return aRetArr;
}

From source file:com.knowgate.lucene.NewsMessageSearcher.java

License:Open Source License

/**
 * Find out if a given NewsMessage is already indexed
 * @param sLuceneIndexPath String Base path for Lucene indexes excluding WorkArea and table name
 * @param sWorkArea String GUID of WorkArea to be searched (optional, may be null)
 * @param sNewsGroupCategoryName String GUID or Category Name of NewsGroup to which message belongs (optional, may be null)
 * @param sAuthor String/*from   w w  w  .j  a v a  2s .c  o m*/
 * @param sTitle String
 * @param sText String
 * @param iLimit int
 * @param oSortBy Comparator
 * @return NewsMessageRecord[] An Array of NewsMessageRecord objects or <b>null</b> if no messages where found matching the given criteria
 * @throws ParseException
 * @throws IOException
 * @throws NullPointerException
 */
public static boolean isIndexed(String sLuceneIndexPath, String sWorkArea, String sNewsGroupCategoryName,
        String sMsgId) throws ParseException, IOException, NullPointerException {

    boolean bIsIndexed = false;

    if (null == sLuceneIndexPath)
        throw new NullPointerException("NewsMessageSearcher.search() luceneindex parameter cannot be null");

    if (DebugFile.trace) {
        DebugFile.writeln("Begin NewsMessageSearcher.isIndexed(" + sLuceneIndexPath + "," + sWorkArea + ","
                + sNewsGroupCategoryName + "," + sMsgId + ")");
        DebugFile.incIdent();
    }

    BooleanQuery oQrx = new BooleanQuery();
    oQrx.add(new TermQuery(new Term("guid", sMsgId)), BooleanClause.Occur.MUST);

    if (null != sWorkArea)
        oQrx.add(new TermQuery(new Term("workarea", sWorkArea)), BooleanClause.Occur.MUST);

    if (null != sNewsGroupCategoryName)
        oQrx.add(new TermQuery(new Term("container", sNewsGroupCategoryName)), BooleanClause.Occur.MUST);

    String sSegments = Gadgets.chomp(sLuceneIndexPath, File.separator) + "k_newsmsgs" + File.separator
            + sWorkArea;
    if (DebugFile.trace)
        DebugFile.writeln("new IndexSearcher(" + sSegments + ")");
    Directory oDir = Indexer.openDirectory(sSegments);
    IndexSearcher oSearch = new IndexSearcher(oDir);

    if (DebugFile.trace)
        DebugFile.writeln("IndexSearcher.search(" + oQrx.toString() + ")");
    TopDocs oTopSet = oSearch.search(oQrx, null, 1);
    if (oTopSet.scoreDocs != null) {
        ScoreDoc[] oTopDoc = oTopSet.scoreDocs;
        bIsIndexed = (oTopDoc.length > 0);
    }
    oSearch.close();
    oDir.close();

    if (DebugFile.trace) {
        DebugFile.decIdent();
        DebugFile.writeln("End NewsMessageSearcher.isIndexed() : " + String.valueOf(bIsIndexed));
    }
    return bIsIndexed;
}

From source file:com.knowgate.lucene.NewsMessageSearcher.java

License:Open Source License

/**
 * Compose a Lucene query based on given parameters
 * @param sLuceneIndexPath String Base path for Lucene indexes excluding WorkArea and table name
 * @param sWorkArea String GUID of WorkArea to be searched, cannot be null
 * @param sGroup sNewsGroupCategoryName String GUID or Category Name of NewsGroup to which message belongs (optional, may be null)
 * @param sAuthor String/*from ww w. j a va 2 s .  c  o m*/
 * @param sTitle String
 * @param sText String
 * @param iLimit int
 * @param oSortBy Comparator
 * @return NewsMessageRecord[] An Array of NewsMessageRecord objects or <b>null</b> if no messages where found matching the given criteria
 * @throws ParseException
 * @throws IOException
 * @throws NullPointerException
 */
public static NewsMessageRecord[] search(String sLuceneIndexPath, String sWorkArea,
        String sNewsGroupCategoryName, String sAuthor, String sTitle, Date dtFromDate, Date dtToDate,
        String sText, int iLimit, Comparator oSortBy) throws ParseException, IOException, NullPointerException {

    if (null == sLuceneIndexPath)
        throw new NullPointerException("NewsMessageSearcher.search() luceneindex parameter cannot be null");

    if (null == sWorkArea)
        throw new NullPointerException("NewsMessageSearcher.search() workarea parameter cannot be null");

    if (DebugFile.trace) {
        DebugFile.writeln("Begin NewsMessageSearcher.search(" + sLuceneIndexPath + "," + sWorkArea + ","
                + sNewsGroupCategoryName + "," + sAuthor + "," + sTitle + "," + dtFromDate + "," + dtToDate
                + "," + sText + "," + String.valueOf(iLimit) + ")");
        DebugFile.incIdent();
    }

    NewsMessageRecord[] aRetArr;

    BooleanQuery oQrx = new BooleanQuery();

    oQrx.add(new TermQuery(new Term("workarea", sWorkArea)), BooleanClause.Occur.MUST);

    if (null != sNewsGroupCategoryName)
        oQrx.add(new TermQuery(new Term("container", sNewsGroupCategoryName)), BooleanClause.Occur.MUST);

    if (dtFromDate != null && dtToDate != null)
        oQrx.add(
                new TermRangeQuery("created", DateTools.dateToString(dtFromDate, DateTools.Resolution.DAY),
                        DateTools.dateToString(dtToDate, DateTools.Resolution.DAY), true, true),
                BooleanClause.Occur.MUST);
    else if (dtFromDate != null)
        oQrx.add(new TermRangeQuery("created", DateTools.dateToString(dtFromDate, DateTools.Resolution.DAY),
                null, true, false), BooleanClause.Occur.MUST);

    else if (dtToDate != null)
        oQrx.add(new TermRangeQuery("created", null, DateTools.dateToString(dtToDate, DateTools.Resolution.DAY),
                false, true), BooleanClause.Occur.MUST);

    BooleanQuery oQry = new BooleanQuery();

    if (null != sAuthor)
        oQry.add(new TermQuery(new Term("author", sAuthor)), BooleanClause.Occur.SHOULD);

    if (null != sTitle)
        oQry.add(new TermQuery(new Term("title", sTitle)), BooleanClause.Occur.SHOULD);

    if (null != sText)
        oQry.add(new TermQuery(new Term("text", escape(Gadgets.ASCIIEncode(sText).toLowerCase()))),
                BooleanClause.Occur.SHOULD);

    oQrx.add(oQry, BooleanClause.Occur.MUST);

    String sSegments = Gadgets.chomp(sLuceneIndexPath, File.separator) + "k_newsmsgs" + File.separator
            + sWorkArea;
    if (DebugFile.trace)
        DebugFile.writeln("new IndexSearcher(" + sSegments + ")");
    Directory oDir = Indexer.openDirectory(sSegments);
    IndexSearcher oSearch = new IndexSearcher(oDir);

    Document oDoc;

    if (DebugFile.trace)
        DebugFile.writeln("IndexSearcher.search(" + oQrx.toString() + ")");
    TopDocs oTopSet = oSearch.search(oQrx, null, iLimit > 0 ? iLimit : 2147483647);
    if (oTopSet.scoreDocs != null) {
        ScoreDoc[] oTopDoc = oTopSet.scoreDocs;
        final int iDocCount = oTopDoc.length <= iLimit ? oTopDoc.length : iLimit;
        aRetArr = new NewsMessageRecord[iDocCount];
        for (int d = 0; d < iDocCount; d++) {
            oDoc = oSearch.doc(oTopDoc[d].doc);
            try {
                aRetArr[d] = new NewsMessageRecord(oTopDoc[d].score, oDoc.get("workarea"), oDoc.get("guid"),
                        oDoc.get("thread"), oDoc.get("container"), oDoc.get("title"), oDoc.get("author"),
                        DateTools.stringToDate(oDoc.get("created")), oDoc.get("abstract"));
            } catch (java.text.ParseException neverthrown) {
                throw new ParseException("NewsMessageSearcher.search() Error parsing date "
                        + oDoc.get("created") + " of document " + oDoc.get("guid"));
            }
        } // next
    } else {
        aRetArr = null;
    }

    oSearch.close();
    oDir.close();

    if (oSortBy != null) {
        Arrays.sort(aRetArr, oSortBy);
    }

    if (DebugFile.trace) {
        DebugFile.decIdent();
        if (null == aRetArr)
            DebugFile.writeln("End NewsMessageSearcher.search() : no records found");
        else
            DebugFile.writeln("End NewsMessageSearcher.search() : " + String.valueOf(aRetArr.length));
    }
    return aRetArr;
}

From source file:com.leavesfly.lia.commom.TestUtil.java

License:Apache License

public static int hitCount(IndexSearcher searcher, Query query, Filter filter) throws IOException {
    return searcher.search(query, filter, 1).totalHits;
}

From source file:com.liusoft.dlog4j.search.SearchProxy.java

License:Open Source License

/**
 * ?//from  www . jav  a2  s.com
 * @param params
 * @return
 * @throws Exception 
 */
public static List search(SearchParameter params) throws Exception {
    if (params == null)
        return null;

    SearchEnabled searching = (SearchEnabled) params.getSearchObject().newInstance();

    StringBuffer path = new StringBuffer(_baseIndexPath);
    path.append(searching.name());
    File f = new File(path.toString());
    if (!f.exists())
        return null;

    IndexSearcher searcher = new IndexSearcher(path.toString());

    //?
    BooleanQuery comboQuery = new BooleanQuery();
    int _query_count = 0;
    StringTokenizer st = new StringTokenizer(params.getSearchKey());
    while (st.hasMoreElements()) {
        String q = st.nextToken();
        String[] indexFields = searching.getIndexFields();
        for (int i = 0; i < indexFields.length; i++) {
            QueryParser qp = new QueryParser(indexFields[i], analyzer);
            try {
                Query subjectQuery = qp.parse(q);
                comboQuery.add(subjectQuery, BooleanClause.Occur.SHOULD);
                _query_count++;
            } catch (Exception e) {
                log.error("Add query parameter failed. key=" + q, e);
            }
        }
    }

    if (_query_count == 0)//?
        return null;

    //??
    MultiFilter multiFilter = null;
    HashMap conds = params.getConditions();
    if (conds != null) {
        Iterator keys = conds.keySet().iterator();
        while (keys.hasNext()) {
            if (multiFilter == null)
                multiFilter = new MultiFilter(0);
            String key = (String) keys.next();
            multiFilter.add(new FieldFilter(key, conds.get(key).toString()));
        }
    }

    /*
     * Creates a sort, possibly in reverse,
     * by terms in the given field with the type of term values explicitly given.
     */
    SortField[] s_fields = new SortField[2];
    s_fields[0] = SortField.FIELD_SCORE;
    s_fields[1] = new SortField(searching.getKeywordField(), SortField.INT, true);
    Sort sort = new Sort(s_fields);

    Hits hits = searcher.search(comboQuery, multiFilter, sort);
    int numResults = hits.length();
    //System.out.println(numResults + " found............................");
    int result_count = Math.min(numResults, MAX_RESULT_COUNT);
    List results = new ArrayList(result_count);
    for (int i = 0; i < result_count; i++) {
        Document doc = (Document) hits.doc(i);
        //Java
        Object result = params.getSearchObject().newInstance();
        Enumeration fields = doc.fields();
        while (fields.hasMoreElements()) {
            Field field = (Field) fields.nextElement();
            //System.out.println(field.name()+" -- "+field.stringValue());
            if (CLASSNAME_FIELD.equals(field.name()))
                continue;
            //?
            if (!field.isStored())
                continue;
            //System.out.println("=========== begin to mapping ============");
            //String --> anything
            Class fieldType = getNestedPropertyType(result, field.name());
            //System.out.println(field.name()+", class = " + fieldType.getName());
            Object fieldValue = null;
            if (fieldType.equals(Date.class))
                fieldValue = new Date(Long.parseLong(field.stringValue()));
            else
                fieldValue = ConvertUtils.convert(field.stringValue(), fieldType);
            //System.out.println(fieldValue+", class = " + fieldValue.getClass().getName());
            setNestedProperty(result, field.name(), fieldValue);
        }
        results.add(result);
    }

    return results;
}

From source file:com.m3958.apps.pcms.lucene.SearchFiles.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  www . j a v a  2  s.c o m
    }

    String index = "c:/lucene/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(new File(index)));
    IndexSearcher searcher = new IndexSearcher(reader);
    //    Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_40);

    Analyzer analyzer = new ComplexAnalyzer();

    BufferedReader in = null;
    if (queries != null) {
        in = new BufferedReader(new InputStreamReader(new FileInputStream(queries), "UTF-8"));
    } else {
        in = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
    }
    QueryParser parser = new QueryParser(Version.LUCENE_45, field, analyzer);

    queryString = "cusvalue";
    while (true) {
        if (queries == null && queryString == null) {// prompt the user
            System.out.println("Enter query: ");
        }

        String line = queryString != null ? queryString : in.readLine();

        if (line == null || line.length() == -1) {
            break;
        }

        line = line.trim();
        if (line.length() == 0) {
            break;
        }

        Query query = parser.parse(line);
        System.out.println("Searching for: " + query.toString(field));

        if (repeat > 0) {// repeat & time as benchmark
            Date start = new Date();
            for (int i = 0; i < repeat; i++) {
                searcher.search(query, null, 100);
            }
            Date end = new Date();
            System.out.println("Time: " + (end.getTime() - start.getTime()) + "ms");
        }

        doPagingSearch(in, searcher, query, hitsPerPage, raw, queries == null && queryString == null);

        if (queryString != null) {
            break;
        }
    }
    reader.close();
}

From source file:com.meltmedia.cadmium.search.SearchService.java

License:Apache License

private Map<String, Object> buildSearchResults(final String query, final String path) throws Exception {
    logger.info("Running search for [{}]", query);
    final Map<String, Object> resultMap = new LinkedHashMap<String, Object>();

    new SearchTemplate(provider) {
        public void doSearch(IndexSearcher index) throws IOException, ParseException {
            QueryParser parser = createParser(getAnalyzer());

            resultMap.put("number-hits", 0);

            List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();

            resultMap.put("results", resultList);

            if (index != null && parser != null) {
                String literalQuery = query.replaceAll(ALLOWED_CHARS_PATTERN, "\\\\$1");
                Query query1 = parser.parse(literalQuery);
                if (StringUtils.isNotBlank(path)) {
                    Query pathPrefix = new PrefixQuery(new Term("path", path));
                    BooleanQuery boolQuery = new BooleanQuery();
                    boolQuery.add(pathPrefix, Occur.MUST);
                    boolQuery.add(query1, Occur.MUST);
                    query1 = boolQuery;//from  w w w  . jav a 2  s . c o  m
                }
                TopDocs results = index.search(query1, null, 100000);
                QueryScorer scorer = new QueryScorer(query1);
                Highlighter highlighter = new Highlighter(new SimpleHTMLFormatter(), new SimpleHTMLEncoder(),
                        scorer);

                logger.info("Search returned {} hits.", results.totalHits);
                resultMap.put("number-hits", results.totalHits);

                for (ScoreDoc doc : results.scoreDocs) {
                    Document document = index.doc(doc.doc);
                    String content = document.get("content");
                    String title = document.get("title");

                    Map<String, Object> result = new LinkedHashMap<String, Object>();
                    String excerpt = "";

                    try {
                        excerpt = highlighter.getBestFragments(
                                parser.getAnalyzer().tokenStream(null, new StringReader(content)), content, 3,
                                "...");
                        excerpt = fixExcerpt(excerpt);

                        result.put("excerpt", excerpt);
                    } catch (Exception e) {
                        logger.debug("Failed to get search excerpt from content.", e);

                        try {
                            excerpt = highlighter.getBestFragments(
                                    parser.getAnalyzer().tokenStream(null, new StringReader(title)), title, 1,
                                    "...");
                            excerpt = fixExcerpt(excerpt);

                            result.put("excerpt", excerpt);
                        } catch (Exception e1) {
                            logger.debug("Failed to get search excerpt from title.", e1);

                            result.put("excerpt", "");
                        }
                    }

                    result.put("score", doc.score);
                    result.put("title", title);
                    result.put("path", document.get("path"));

                    resultList.add(result);
                }
            }

        }
    }.search();

    return resultMap;
}

From source file:com.mylucene.basiclucene.SearchFiles.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);/* www  .  ja va  2s.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(new File(index)));
    IndexSearcher searcher = new IndexSearcher(reader);
    Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_44);

    BufferedReader in = null;
    if (queries != null) {
        in = new BufferedReader(new InputStreamReader(new FileInputStream(queries), "UTF-8"));
    } else {
        in = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
    }
    QueryParser parser = new QueryParser(Version.LUCENE_44, field, analyzer);
    while (true) {
        if (queries == null && queryString == null) { // prompt the user
            System.out.println("Enter query: ");
        }

        String line = queryString != null ? queryString : in.readLine();

        if (line == null || line.length() == -1) {
            break;
        }

        line = line.trim();
        if (line.length() == 0) {
            break;
        }

        Query query = parser.parse(line);
        System.out.println("Searching for: " + query.toString(field));

        if (repeat > 0) { // repeat & time as benchmark
            Date start = new Date();
            for (int i = 0; i < repeat; i++) {
                searcher.search(query, null, 100);
            }
            Date end = new Date();
            System.out.println("Time: " + (end.getTime() - start.getTime()) + "ms");
        }

        doPagingSearch(in, searcher, query, hitsPerPage, raw, queries == null && queryString == null);

        if (queryString != null) {
            break;
        }
    }
    reader.close();
}

From source file:com.nero.model.SearchFiles.java

License:Apache License

/** Simple command-line based search demo. */
public static void main(String[] args) throws Exception {
    testSearch();/*from  w  w  w . j a  v  a 2  s . c  om*/
    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/java/4_0/demo.html for details.";
    if (args.length > 0 && ("-h".equals(args[0]) || "-help".equals(args[0]))) {
        System.out.println(usage);
        System.exit(0);
    }

    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 = IndexReader.open(FSDirectory.open(new File(index)));
    IndexSearcher searcher = new IndexSearcher(reader);
    Analyzer analyzer = new IKAnalyzer();

    BufferedReader in = null;
    if (queries != null) {
        in = new BufferedReader(new InputStreamReader(new FileInputStream(queries), "UTF-8"));
    } else {
        in = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
    }
    QueryParser parser = new QueryParser(Version.LUCENE_31, field, analyzer);
    while (true) {
        if (queries == null && queryString == null) { // prompt the user
            System.out.println("Enter query: ");
        }

        String line = queryString != null ? queryString : in.readLine();

        System.out.println(line);

        if (line == null || line.length() == -1) {
            break;
        }

        line = line.trim();
        if (line.length() == 0) {
            break;
        }

        Query query = parser.parse(line);
        System.out.println("Searching for: " + query.toString(field));

        if (repeat > 0) { // repeat & time as benchmark
            Date start = new Date();
            for (int i = 0; i < repeat; i++) {
                searcher.search(query, null, 100);
            }
            Date end = new Date();
            System.out.println("Time: " + (end.getTime() - start.getTime()) + "ms");
        }

        doPagingSearch(in, searcher, query, hitsPerPage, raw, queries == null && queryString == null);

        if (queryString != null) {
            break;
        }
    }
    searcher.close();
    reader.close();
}