Search in sources :

Example 6 with MatchQueryBuilder

use of org.elasticsearch.index.query.MatchQueryBuilder in project elasticsearch by elastic.

the class TransportTwoNodesSearchIT method testFailedMultiSearchWithWrongQuery.

public void testFailedMultiSearchWithWrongQuery() throws Exception {
    prepareData();
    logger.info("Start Testing failed multi search with a wrong query");
    MultiSearchResponse response = client().prepareMultiSearch().add(client().prepareSearch("test").setQuery(new MatchQueryBuilder("foo", "biz"))).add(client().prepareSearch("test").setQuery(QueryBuilders.termQuery("nid", 2))).add(client().prepareSearch("test").setQuery(QueryBuilders.matchAllQuery())).execute().actionGet();
    assertThat(response.getResponses().length, equalTo(3));
    assertThat(response.getResponses()[0].getFailureMessage(), notNullValue());
    assertThat(response.getResponses()[1].getFailureMessage(), nullValue());
    assertThat(response.getResponses()[1].getResponse().getHits().getHits().length, equalTo(1));
    assertThat(response.getResponses()[2].getFailureMessage(), nullValue());
    assertThat(response.getResponses()[2].getResponse().getHits().getHits().length, equalTo(10));
    logger.info("Done Testing failed search");
}
Also used : MultiSearchResponse(org.elasticsearch.action.search.MultiSearchResponse) MatchQueryBuilder(org.elasticsearch.index.query.MatchQueryBuilder)

Example 7 with MatchQueryBuilder

use of org.elasticsearch.index.query.MatchQueryBuilder in project elasticsearch by elastic.

the class TransportTwoNodesSearchIT method testFailedSearchWithWrongQuery.

public void testFailedSearchWithWrongQuery() throws Exception {
    prepareData();
    NumShards test = getNumShards("test");
    logger.info("Start Testing failed search with wrong query");
    try {
        SearchResponse searchResponse = client().search(searchRequest("test").source(new SearchSourceBuilder().query(new MatchQueryBuilder("foo", "biz")))).actionGet();
        assertThat(searchResponse.getTotalShards(), equalTo(test.numPrimaries));
        assertThat(searchResponse.getSuccessfulShards(), equalTo(0));
        assertThat(searchResponse.getFailedShards(), equalTo(test.numPrimaries));
        fail("search should fail");
    } catch (ElasticsearchException e) {
        assertThat(e.unwrapCause(), instanceOf(SearchPhaseExecutionException.class));
    // all is well
    }
    logger.info("Done Testing failed search");
}
Also used : MatchQueryBuilder(org.elasticsearch.index.query.MatchQueryBuilder) ElasticsearchException(org.elasticsearch.ElasticsearchException) SearchResponse(org.elasticsearch.action.search.SearchResponse) MultiSearchResponse(org.elasticsearch.action.search.MultiSearchResponse) SearchSourceBuilder(org.elasticsearch.search.builder.SearchSourceBuilder)

Example 8 with MatchQueryBuilder

use of org.elasticsearch.index.query.MatchQueryBuilder in project elasticsearch by elastic.

the class ChildQuerySearchIT method testHighlightersIgnoreParentChild.

public void testHighlightersIgnoreParentChild() {
    assertAcked(prepareCreate("test").addMapping("parent-type", "searchText", "type=text,term_vector=with_positions_offsets,index_options=offsets").addMapping("child-type", "_parent", "type=parent-type", "searchText", "type=text,term_vector=with_positions_offsets,index_options=offsets"));
    client().prepareIndex("test", "parent-type", "parent-id").setSource("searchText", "quick brown fox").get();
    client().prepareIndex("test", "child-type", "child-id").setParent("parent-id").setSource("searchText", "quick brown fox").get();
    refresh();
    String[] highlightTypes = new String[] { "plain", "fvh", "postings" };
    for (String highlightType : highlightTypes) {
        logger.info("Testing with highlight type [{}]", highlightType);
        SearchResponse searchResponse = client().prepareSearch("test").setQuery(new BoolQueryBuilder().must(new MatchQueryBuilder("searchText", "fox")).must(new HasChildQueryBuilder("child-type", new MatchAllQueryBuilder(), ScoreMode.None))).highlighter(new HighlightBuilder().field(new HighlightBuilder.Field("searchText").highlighterType(highlightType))).get();
        assertHitCount(searchResponse, 1);
        assertThat(searchResponse.getHits().getAt(0).getId(), equalTo("parent-id"));
        HighlightField highlightField = searchResponse.getHits().getAt(0).getHighlightFields().get("searchText");
        assertThat(highlightField.getFragments()[0].string(), equalTo("quick brown <em>fox</em>"));
        searchResponse = client().prepareSearch("test").setQuery(new BoolQueryBuilder().must(new MatchQueryBuilder("searchText", "fox")).must(new HasParentQueryBuilder("parent-type", new MatchAllQueryBuilder(), false))).highlighter(new HighlightBuilder().field(new HighlightBuilder.Field("searchText").highlighterType(highlightType))).get();
        assertHitCount(searchResponse, 1);
        assertThat(searchResponse.getHits().getAt(0).getId(), equalTo("child-id"));
        highlightField = searchResponse.getHits().getAt(0).getHighlightFields().get("searchText");
        assertThat(highlightField.getFragments()[0].string(), equalTo("quick brown <em>fox</em>"));
    }
}
Also used : Field(org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder.Field) HighlightField(org.elasticsearch.search.fetch.subphase.highlight.HighlightField) BoolQueryBuilder(org.elasticsearch.index.query.BoolQueryBuilder) HasParentQueryBuilder(org.elasticsearch.index.query.HasParentQueryBuilder) MatchQueryBuilder(org.elasticsearch.index.query.MatchQueryBuilder) HighlightField(org.elasticsearch.search.fetch.subphase.highlight.HighlightField) Matchers.containsString(org.hamcrest.Matchers.containsString) HighlightBuilder(org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder) SearchResponse(org.elasticsearch.action.search.SearchResponse) HasChildQueryBuilder(org.elasticsearch.index.query.HasChildQueryBuilder) MatchAllQueryBuilder(org.elasticsearch.index.query.MatchAllQueryBuilder) Field(org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder.Field)

Example 9 with MatchQueryBuilder

use of org.elasticsearch.index.query.MatchQueryBuilder in project bw-calendar-engine by Bedework.

the class BwIndexEsImpl method search.

@Override
public SearchResult search(final String query, final boolean relevance, final FilterBase filter, final List<SortTerm> sort, final FilterBase defaultFilterContext, final String start, final String end, final int pageSize, final DeletedState deletedState, final RecurringRetrievalMode recurRetrieval) throws CalFacadeException {
    if (basicSysprops.getTestMode()) {
        final long timeSinceIndex = System.currentTimeMillis() - lastIndexTime;
        final long waitTime = indexerDelay - timeSinceIndex;
        if (waitTime > 0) {
            try {
                Thread.sleep(waitTime);
            } catch (final InterruptedException ignored) {
            }
        }
    }
    final EsSearchResult res = new EsSearchResult(this);
    res.start = start;
    res.end = end;
    res.pageSize = pageSize;
    res.accessCheck = accessCheck;
    res.delState = deletedState;
    res.recurRetrieval = recurRetrieval;
    if (query != null) {
        final MatchQueryBuilder mqb = QueryBuilders.matchQuery("_all", query);
        if (!relevance) {
            mqb.operator(Operator.AND);
        } else {
            mqb.fuzziness("1");
            mqb.prefixLength(2);
        }
        res.curQuery = mqb;
    // res.curQuery = QueryBuilders.queryString(query);
    }
    final ESQueryFilter ef = getFilters(recurRetrieval);
    res.curFilter = ef.buildFilter(filter);
    if (res.curFilter instanceof MatchNone) {
        res.setFound(0);
        return res;
    }
    res.curFilter = ef.addDateRangeFilter(res.curFilter, IcalDefs.entityTypeEvent, start, end);
    res.curFilter = ef.addLimits(res.curFilter, defaultFilterContext, res.delState);
    if (res.curFilter instanceof MatchNone) {
        res.setFound(0);
        return res;
    }
    res.requiresSecondaryFetch = ef.requiresSecondaryFetch();
    // res.canPage = ef.canPage();
    res.curSort = sort;
    final SearchRequestBuilder srb = getClient().prepareSearch(searchIndexes);
    if (res.curQuery != null) {
        srb.setQuery(res.curQuery);
    }
    srb.setSearchType(SearchType.COUNT).setPostFilter(res.curFilter).setFrom(0).setSize(0);
    if (!Util.isEmpty(res.curSort)) {
        SortOrder so;
        for (final SortTerm st : res.curSort) {
            if (st.isAscending()) {
                so = SortOrder.ASC;
            } else {
                so = SortOrder.DESC;
            }
            srb.addSort(new FieldSortBuilder(ESQueryFilter.makePropertyRef(st.getProperties())).order(so));
        }
    }
    res.latestStart = ef.getLatestStart();
    res.earliestEnd = ef.getEarliestEnd();
    if (debug) {
        debug("Search: latestStart=" + res.latestStart + " earliestEnd=" + res.earliestEnd + " targetIndex=" + targetIndex + "; srb=" + srb);
    }
    final SearchResponse resp = srb.execute().actionGet();
    if (debug) {
        debug("Search: returned status " + resp.status() + " found: " + resp.getHits().getTotalHits());
    }
    res.setFound(resp.getHits().getTotalHits());
    return res;
}
Also used : SortTerm(org.bedework.calfacade.filter.SortTerm) SearchRequestBuilder(org.elasticsearch.action.search.SearchRequestBuilder) MatchQueryBuilder(org.elasticsearch.index.query.MatchQueryBuilder) SortOrder(org.elasticsearch.search.sort.SortOrder) FieldSortBuilder(org.elasticsearch.search.sort.FieldSortBuilder) SearchResponse(org.elasticsearch.action.search.SearchResponse)

Example 10 with MatchQueryBuilder

use of org.elasticsearch.index.query.MatchQueryBuilder in project bw-calendar-engine by Bedework.

the class ESQueryFilter method makeFilter.

private FilterBuilder makeFilter(final PropertyInfoIndex pii, final String path, final Object val, final OperationType opType) throws CalFacadeException {
    final BwIcalPropertyInfoEntry bwPie = BwIcalPropertyInfo.getPinfo(pii);
    switch(opType) {
        case compare:
            if (bwPie.getAnalyzed()) {
                if (val instanceof Collection) {
                    final String[] vals;
                    try {
                        final Collection valsC = (Collection) val;
                        vals = (String[]) (valsC).toArray(new String[valsC.size()]);
                    } catch (final Throwable t) {
                        throw new CalFacadeException(CalFacadeException.filterBadOperator, "Invalid query. Multi match only allowed on strings");
                    }
                    final MultiMatchQueryBuilder mmqb = new MultiMatchQueryBuilder(path, vals);
                    return new QueryFilterBuilder(mmqb);
                }
                return new QueryFilterBuilder(new MatchQueryBuilder(path, val));
            }
            if (val instanceof Collection) {
                final TermsFilterBuilder tfb = FilterBuilders.termsFilter(path, (Collection) val);
                tfb.execution("or");
                return tfb;
            }
            return new TermFilterBuilder(path, val);
        case timeRange:
            final RangeFilterBuilder rfb = FilterBuilders.rangeFilter(path);
            final TimeRange tr = (TimeRange) val;
            if (tr.getEnd() == null) {
                rfb.gte(tr.getStart().toString());
                return rfb;
            }
            if (tr.getStart() == null) {
                rfb.lt(tr.getEnd().toString());
                return rfb;
            }
            rfb.from(tr.getStart().toString());
            rfb.to(tr.getEnd().toString());
            rfb.includeLower(true);
            rfb.includeUpper(false);
            return rfb;
        case absence:
            return FilterBuilders.missingFilter(path);
        case presence:
            return FilterBuilders.existsFilter(path);
        case prefix:
            return FilterBuilders.prefixFilter(path, (String) val);
        default:
            throw new CalFacadeException(CalFacadeException.filterBadOperator, opType.toString());
    }
}
Also used : RangeFilterBuilder(org.elasticsearch.index.query.RangeFilterBuilder) TermsFilterBuilder(org.elasticsearch.index.query.TermsFilterBuilder) MultiMatchQueryBuilder(org.elasticsearch.index.query.MultiMatchQueryBuilder) QueryFilterBuilder(org.elasticsearch.index.query.QueryFilterBuilder) CalFacadeException(org.bedework.calfacade.exc.CalFacadeException) TimeRange(org.bedework.caldav.util.TimeRange) BwIcalPropertyInfoEntry(org.bedework.calfacade.ical.BwIcalPropertyInfo.BwIcalPropertyInfoEntry) TermFilterBuilder(org.elasticsearch.index.query.TermFilterBuilder) Collection(java.util.Collection) MultiMatchQueryBuilder(org.elasticsearch.index.query.MultiMatchQueryBuilder) MatchQueryBuilder(org.elasticsearch.index.query.MatchQueryBuilder)

Aggregations

MatchQueryBuilder (org.elasticsearch.index.query.MatchQueryBuilder)10 SearchResponse (org.elasticsearch.action.search.SearchResponse)7 MultiMatchQueryBuilder (org.elasticsearch.index.query.MultiMatchQueryBuilder)4 ElasticsearchException (org.elasticsearch.ElasticsearchException)2 IndexRequestBuilder (org.elasticsearch.action.index.IndexRequestBuilder)2 MultiSearchResponse (org.elasticsearch.action.search.MultiSearchResponse)2 SearchHits (org.elasticsearch.search.SearchHits)2 SearchSourceBuilder (org.elasticsearch.search.builder.SearchSourceBuilder)2 Field (org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder.Field)2 ElasticsearchAssertions.assertSearchHits (org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchHits)2 ElasticsearchAssertions.assertSearchResponse (org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse)2 Matchers.containsString (org.hamcrest.Matchers.containsString)2 ArrayList (java.util.ArrayList)1 Collection (java.util.Collection)1 Random (java.util.Random)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 AtomicLong (java.util.concurrent.atomic.AtomicLong)1 TimeRange (org.bedework.caldav.util.TimeRange)1 CalFacadeException (org.bedework.calfacade.exc.CalFacadeException)1 SortTerm (org.bedework.calfacade.filter.SortTerm)1