@Test
public void testDoQueryForSubstring() {

    String field = "name";
    String searchString = "foo";
    // tokenize the pattern using the given analyzer
    List<String> terms = new ArrayList<>();
    try (TokenStream stream = analyzer.tokenStream(field, new StringReader(QueryParser.escape(searchString)))) {
        stream.reset();
        CharTermAttribute termAtt = stream.addAttribute(CharTermAttribute.class);
        while (stream.incrementToken()) {
            terms.add(termAtt.toString());
        }
    }
    catch (IOException e) {
        e.printStackTrace();
        fail("Can't parse search string");
    }
    Query q;
    if (terms.size() == 1) {
        // create a simple term query
        q = new TermQuery(new Term(field, terms.get(0)));
    }
    else {
        // create a span query
        List<SpanQuery> stqs = new ArrayList<>();
        for (String term : terms) {
            stqs.add(new SpanTermQuery(new Term(field, term)));
        }
        q = new SpanNearQuery(stqs.toArray(new SpanQuery[stqs.size()]), 1, false);
    }
    Collection<String> results;
    try {
        results = searchService.doQuery(q, new SingleFieldStringMapper(field));
        for (String s : results) {
            System.out.println("Next result: '" + s + "'");
        }
        assertEquals("Wrong number of results", 4, results.size());
        assertTrue(results.contains("foo"));
        assertTrue(results.contains("foo bar"));
        assertTrue(results.contains("foo bar baz"));
        assertTrue(results.contains("foo baz"));
    }
    catch (Exception e) {
        e.printStackTrace();
        fail("Query failed");
    }
}