Example usage for org.apache.lucene.queryparser.flexible.standard StandardQueryParser parse

List of usage examples for org.apache.lucene.queryparser.flexible.standard StandardQueryParser parse

Introduction

In this page you can find the example usage for org.apache.lucene.queryparser.flexible.standard StandardQueryParser parse.

Prototype

@Override
public Query parse(String query, String defaultField) throws QueryNodeException 

Source Link

Document

Overrides QueryParserHelper#parse(String,String) so it casts the return object to Query .

Usage

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 w  w .j  a  v  a 2  s .  com
    }

    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:aos.lucene.tools.FlexibleQueryParserTest.java

License:Apache License

public void testSimple() throws Exception {
    Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_46);
    StandardQueryParser parser = new StandardQueryParser(analyzer);
    Query q = null;/*from  w w w .ja v a 2  s . c  om*/
    try {
        q = parser.parse("(agile OR extreme) AND methodology", "subject");
    } catch (QueryNodeException exc) {
        // TODO: handle exc
    }
    LOGGER.info("parsed " + q);
}

From source file:aos.lucene.tools.FlexibleQueryParserTest.java

License:Apache License

public void testNoFuzzyOrWildcard() throws Exception {
    Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_46);
    StandardQueryParser parser = new CustomFlexibleQueryParser(analyzer);
    try {/*from  www .j a  va2 s.c  o m*/
        parser.parse("agil*", "subject");
        fail("didn't hit expected exception");
    } catch (QueryNodeException exc) {
        // expected
    }

    try {
        parser.parse("agil~0.8", "subject");
        fail("didn't hit expected exception");
    } catch (QueryNodeException exc) {
        // expected
    }
}

From source file:aos.lucene.tools.FlexibleQueryParserTest.java

License:Apache License

public void testPhraseQuery() throws Exception {
    Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_46);
    StandardQueryParser parser = new CustomFlexibleQueryParser(analyzer);

    Query query = parser.parse("singleTerm", "subject");
    assertTrue("TermQuery", query instanceof TermQuery);

    query = parser.parse("\"a phrase test\"", "subject");
    LOGGER.info("got query=" + query);
    assertTrue("SpanNearQuery", query instanceof SpanNearQuery);
}

From source file:at.ac.univie.mminf.luceneSKOS.test.SKOSLabelFilterTest.java

License:Apache License

@Test
public void testTermQuery() throws IOException, QueryNodeException {
    Document doc = new Document();
    doc.add(new Field("content", "I work for the united nations", TextField.TYPE_STORED));
    writer.addDocument(doc);/*from  www . ja  v  a  2 s.  c  o  m*/
    searcher = new IndexSearcher(DirectoryReader.open(writer, false));
    StandardQueryParser parser = new StandardQueryParser(new SimpleAnalyzer());
    Query query = parser.parse("united nations", "content");
    assertEquals(1, searcher.search(query, 1).totalHits);
}

From source file:com.foundationdb.server.service.text.FullTextIndexInfosImpl.java

License:Open Source License

@Override
public Query parseQuery(QueryContext context, IndexName name, String defaultField, String query) {
    FullTextIndexInfo index = getIndex(context.getSession(), name, null);
    if (defaultField == null) {
        defaultField = index.getDefaultFieldName();
    }/*from  w  w  w  .  jav  a2 s .c  o m*/
    StandardQueryParser parser = index.getParser();
    try {
        synchronized (parser) {
            return parser.parse(query, defaultField);
        }
    } catch (QueryNodeException ex) {
        throw new FullTextQueryParseException(ex);
    }
}

From source file:com.mathworks.xzheng.tools.FlexibleQueryParserTest.java

License:Apache License

public void testSimple() throws Exception {
    Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_46);
    StandardQueryParser parser = new StandardQueryParser(analyzer);
    Query q = null;/* www.j  a  va 2 s . c om*/
    try {
        q = parser.parse("(agile OR extreme) AND methodology", "subject");
    } catch (QueryNodeException exc) {
        // TODO: handle exc
    }
    System.out.println("parsed " + q);
}

From source file:com.mathworks.xzheng.tools.FlexibleQueryParserTest.java

License:Apache License

public void testPhraseQuery() throws Exception {
    Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_46);
    StandardQueryParser parser = new CustomFlexibleQueryParser(analyzer);

    Query query = parser.parse("singleTerm", "subject");
    assertTrue("TermQuery", query instanceof TermQuery);

    query = parser.parse("\"a phrase test\"", "subject");
    System.out.println("got query=" + query);
    assertTrue("SpanNearQuery", query instanceof SpanNearQuery);
}

From source file:com.netcrest.pado.index.provider.lucene.LuceneBuilder.java

License:Open Source License

private void updateKeyMapDocument(StandardQueryParser parser, IndexWriter writer, ITemporalList tl,
        ITemporalKey tk, ITemporalData data, long endWrittenTime, LuceneField luceneField, KeyType keyType,
        KeyMap keyMap, Set<String> keyTypeNameSet, boolean isIdentityKeyPrimitive, SimpleDateFormat format)
        throws IOException {
    Query query = null;/* ww w  . j  a  v a  2  s  .  c o  m*/
    try {
        String queryString = String.format(TEMPORAL_KEY_QUERY_PREDICATE, tk.getIdentityKey(),
                tk.getStartValidTime(), tk.getEndValidTime(), tk.getWrittenTime());
        query = parser.parse(queryString, "__doc");
    } catch (Exception ex) {
        // Lucene 4.7 bug, internal message not serializable
        // Send message instead of nesting the cause.
        throw new RuntimeException(ex.getMessage());
    }

    writer.deleteDocuments(query);

    Document doc = createKeyMapDocument(parser, writer, tk, data, endWrittenTime, luceneField, keyType, keyMap,
            keyTypeNameSet, isIdentityKeyPrimitive, false, format);
    writer.addDocument(doc);
}

From source file:com.netcrest.pado.index.provider.lucene.LuceneBuilder.java

License:Open Source License

private void updatePojoDocument(StandardQueryParser parser, IndexSearcher searcher, IndexWriter writer,
        ITemporalKey tk, ITemporalData data, long endWrittenTime, LuceneField luceneField,
        Method[] attributeGetters, boolean isIdentityKeyPrimitive, SimpleDateFormat format)
        throws IOException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    Query query = null;/*  w w  w.ja v a2  s . c o  m*/
    try {
        String queryString = String.format(TEMPORAL_KEY_QUERY_PREDICATE, tk.getIdentityKey(),
                tk.getStartValidTime(), tk.getEndValidTime(), tk.getWrittenTime());
        query = parser.parse(queryString, "__doc");
    } catch (Exception ex) {
        // Lucene 4.7 bug, internal message not serializable
        // Send message instead of nesting the cause.
        throw new RuntimeException(ex.getMessage());
    }

    writer.deleteDocuments(query);

    Document doc = createPojoDocument(parser, writer, tk, data, endWrittenTime, luceneField, attributeGetters,
            isIdentityKeyPrimitive, false, format);
    writer.addDocument(doc);
}