Search in sources :

Example 81 with SearchHit

use of org.elasticsearch.search.SearchHit in project fess by codelibs.

the class EsAbstractBehavior method delegateQueryDelete.

@Override
protected int delegateQueryDelete(final ConditionBean cb, final DeleteOption<? extends ConditionBean> option) {
    SearchResponse response = null;
    int count = 0;
    while (true) {
        if (response == null) {
            final SearchRequestBuilder builder = client.prepareSearch(asEsIndex()).setTypes(asEsIndexType()).setScroll(scrollForDelete).setSize(sizeForDelete);
            final EsAbstractConditionBean esCb = (EsAbstractConditionBean) cb;
            if (esCb.getPreference() != null) {
                esCb.setPreference(esCb.getPreference());
            }
            esCb.request().build(builder);
            response = esCb.build(builder).execute().actionGet(scrollSearchTimeout);
        } else {
            final String scrollId = response.getScrollId();
            response = client.prepareSearchScroll(scrollId).setScroll(scrollForDelete).execute().actionGet(scrollSearchTimeout);
        }
        final SearchHits searchHits = response.getHits();
        final SearchHit[] hits = searchHits.getHits();
        if (hits.length == 0) {
            break;
        }
        final BulkRequestBuilder bulkRequest = client.prepareBulk();
        for (final SearchHit hit : hits) {
            bulkRequest.add(client.prepareDelete(asEsIndex(), asEsIndexType(), hit.getId()));
        }
        count += hits.length;
        final BulkResponse bulkResponse = bulkRequest.execute().actionGet(bulkTimeout);
        if (bulkResponse.hasFailures()) {
            throw new IllegalBehaviorStateException(bulkResponse.buildFailureMessage());
        }
    }
    return count;
}
Also used : SearchRequestBuilder(org.elasticsearch.action.search.SearchRequestBuilder) SearchHit(org.elasticsearch.search.SearchHit) IllegalBehaviorStateException(org.dbflute.exception.IllegalBehaviorStateException) BulkResponse(org.elasticsearch.action.bulk.BulkResponse) SearchHits(org.elasticsearch.search.SearchHits) BulkRequestBuilder(org.elasticsearch.action.bulk.BulkRequestBuilder) SearchResponse(org.elasticsearch.action.search.SearchResponse)

Example 82 with SearchHit

use of org.elasticsearch.search.SearchHit in project fess by codelibs.

the class EsAbstractBehavior method delegateQueryDelete.

@Override
protected int delegateQueryDelete(final ConditionBean cb, final DeleteOption<? extends ConditionBean> option) {
    SearchResponse response = null;
    int count = 0;
    while (true) {
        if (response == null) {
            final SearchRequestBuilder builder = client.prepareSearch(asEsIndex()).setTypes(asEsIndexType()).setScroll(scrollForDelete).setSize(sizeForDelete);
            final EsAbstractConditionBean esCb = (EsAbstractConditionBean) cb;
            if (esCb.getPreference() != null) {
                esCb.setPreference(esCb.getPreference());
            }
            esCb.request().build(builder);
            response = esCb.build(builder).execute().actionGet(scrollSearchTimeout);
        } else {
            final String scrollId = response.getScrollId();
            response = client.prepareSearchScroll(scrollId).setScroll(scrollForDelete).execute().actionGet(scrollSearchTimeout);
        }
        final SearchHits searchHits = response.getHits();
        final SearchHit[] hits = searchHits.getHits();
        if (hits.length == 0) {
            break;
        }
        final BulkRequestBuilder bulkRequest = client.prepareBulk();
        for (final SearchHit hit : hits) {
            bulkRequest.add(client.prepareDelete(asEsIndex(), asEsIndexType(), hit.getId()));
        }
        count += hits.length;
        final BulkResponse bulkResponse = bulkRequest.execute().actionGet(bulkTimeout);
        if (bulkResponse.hasFailures()) {
            throw new IllegalBehaviorStateException(bulkResponse.buildFailureMessage());
        }
    }
    return count;
}
Also used : SearchRequestBuilder(org.elasticsearch.action.search.SearchRequestBuilder) SearchHit(org.elasticsearch.search.SearchHit) IllegalBehaviorStateException(org.dbflute.exception.IllegalBehaviorStateException) BulkResponse(org.elasticsearch.action.bulk.BulkResponse) SearchHits(org.elasticsearch.search.SearchHits) BulkRequestBuilder(org.elasticsearch.action.bulk.BulkRequestBuilder) SearchResponse(org.elasticsearch.action.search.SearchResponse)

Example 83 with SearchHit

use of org.elasticsearch.search.SearchHit in project fess by codelibs.

the class EsAbstractBehavior method delegateBulkRequest.

protected void delegateBulkRequest(final ConditionBean cb, Function<SearchHits, Boolean> handler) {
    SearchResponse response = null;
    while (true) {
        if (response == null) {
            final SearchRequestBuilder builder = client.prepareSearch(asEsIndex()).setTypes(asEsIndexType()).setScroll(scrollForCursor).setSize(sizeForCursor);
            final EsAbstractConditionBean esCb = (EsAbstractConditionBean) cb;
            if (esCb.getPreference() != null) {
                builder.setPreference(esCb.getPreference());
            }
            esCb.request().build(builder);
            response = esCb.build(builder).execute().actionGet(scrollSearchTimeout);
        } else {
            final String scrollId = response.getScrollId();
            response = client.prepareSearchScroll(scrollId).setScroll(scrollForDelete).execute().actionGet(scrollSearchTimeout);
        }
        final SearchHits searchHits = response.getHits();
        final SearchHit[] hits = searchHits.getHits();
        if (hits.length == 0) {
            break;
        }
        if (!handler.apply(searchHits)) {
            break;
        }
    }
}
Also used : SearchRequestBuilder(org.elasticsearch.action.search.SearchRequestBuilder) SearchHit(org.elasticsearch.search.SearchHit) SearchHits(org.elasticsearch.search.SearchHits) SearchResponse(org.elasticsearch.action.search.SearchResponse)

Example 84 with SearchHit

use of org.elasticsearch.search.SearchHit in project fess by codelibs.

the class QueryResponseList method init.

public void init(final OptionalEntity<SearchResponse> searchResponseOpt, final int start, final int pageSize) {
    searchResponseOpt.ifPresent(searchResponse -> {
        final FessConfig fessConfig = ComponentUtil.getFessConfig();
        final SearchHits searchHits = searchResponse.getHits();
        allRecordCount = searchHits.getTotalHits();
        queryTime = searchResponse.getTookInMillis();
        if (searchResponse.getTotalShards() != searchResponse.getSuccessfulShards()) {
            partialResults = true;
        }
        final QueryHelper queryHelper = ComponentUtil.getQueryHelper();
        final String hlPrefix = queryHelper.getHighlightPrefix();
        for (final SearchHit searchHit : searchHits.getHits()) {
            final Map<String, Object> docMap = parseSearchHit(fessConfig, hlPrefix, searchHit);
            if (fessConfig.isResultCollapsed()) {
                final Map<String, SearchHits> innerHits = searchHit.getInnerHits();
                if (innerHits != null) {
                    final SearchHits innerSearchHits = innerHits.get(fessConfig.getQueryCollapseInnerHitsName());
                    if (innerSearchHits != null) {
                        final long totalHits = innerSearchHits.getTotalHits();
                        if (totalHits > 1) {
                            docMap.put(fessConfig.getQueryCollapseInnerHitsName() + "_count", totalHits);
                            final SearchHitField bitsField = searchHit.getFields().get(fessConfig.getIndexFieldContentMinhashBits());
                            if (bitsField != null && !bitsField.getValues().isEmpty()) {
                                docMap.put(fessConfig.getQueryCollapseInnerHitsName() + "_hash", bitsField.getValues().get(0));
                            }
                            docMap.put(fessConfig.getQueryCollapseInnerHitsName(), StreamUtil.stream(innerSearchHits.getHits()).get(stream -> stream.map(v -> parseSearchHit(fessConfig, hlPrefix, v)).toArray(n -> new Map[n])));
                        }
                    }
                }
            }
            parent.add(docMap);
        }
        final Aggregations aggregations = searchResponse.getAggregations();
        if (aggregations != null) {
            facetResponse = new FacetResponse(aggregations);
        }
    });
    calculatePageInfo(start, pageSize);
}
Also used : SearchHit(org.elasticsearch.search.SearchHit) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) ListIterator(java.util.ListIterator) SearchHits(org.elasticsearch.search.SearchHits) Aggregations(org.elasticsearch.search.aggregations.Aggregations) OptionalEntity(org.dbflute.optional.OptionalEntity) Collection(java.util.Collection) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) StringUtils(org.apache.commons.lang3.StringUtils) ArrayList(java.util.ArrayList) List(java.util.List) FessConfig(org.codelibs.fess.mylasta.direction.FessConfig) StreamUtil(org.codelibs.core.stream.StreamUtil) Text(org.elasticsearch.common.text.Text) SearchHitField(org.elasticsearch.search.SearchHitField) Map(java.util.Map) QueryHelper(org.codelibs.fess.helper.QueryHelper) SearchResponse(org.elasticsearch.action.search.SearchResponse) HighlightField(org.elasticsearch.search.fetch.subphase.highlight.HighlightField) ViewHelper(org.codelibs.fess.helper.ViewHelper) SearchHit(org.elasticsearch.search.SearchHit) Aggregations(org.elasticsearch.search.aggregations.Aggregations) FessConfig(org.codelibs.fess.mylasta.direction.FessConfig) QueryHelper(org.codelibs.fess.helper.QueryHelper) SearchHitField(org.elasticsearch.search.SearchHitField) SearchHits(org.elasticsearch.search.SearchHits)

Example 85 with SearchHit

use of org.elasticsearch.search.SearchHit in project xmall by Exrick.

the class SearchServiceImpl method search.

@Override
public SearchResult search(String key, int page, int size, String sort, int priceGt, int priceLte) {
    try {
        Settings settings = Settings.builder().put("cluster.name", ES_CLUSTER_NAME).build();
        TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(new TransportAddress(InetAddress.getByName(ES_CONNECT_IP), 9300));
        SearchResult searchResult = new SearchResult();
        // 设置查询条件
        QueryBuilder qb = matchQuery("productName", key);
        // 设置分页
        if (page <= 0) {
            page = 1;
        }
        int start = (page - 1) * size;
        // 设置高亮显示
        HighlightBuilder hiBuilder = new HighlightBuilder();
        hiBuilder.preTags("<a style=\"color: #e4393c\">");
        hiBuilder.postTags("</a>");
        hiBuilder.field("productName");
        // 执行搜索
        SearchResponse searchResponse = null;
        if (priceGt >= 0 && priceLte >= 0 && sort.isEmpty()) {
            searchResponse = client.prepareSearch(ITEM_INDEX).setTypes(ITEM_TYPE).setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setQuery(// Query
            qb).setFrom(start).setSize(size).setExplain(// 从第几个开始,显示size个数据
            true).highlighter(// 设置高亮显示
            hiBuilder).setPostFilter(// 过滤条件
            QueryBuilders.rangeQuery("salePrice").gt(priceGt).lt(priceLte)).get();
        } else if (priceGt >= 0 && priceLte >= 0 && sort.equals("1")) {
            searchResponse = client.prepareSearch(ITEM_INDEX).setTypes(ITEM_TYPE).setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setQuery(// Query
            qb).setFrom(start).setSize(size).setExplain(// 从第几个开始,显示size个数据
            true).highlighter(// 设置高亮显示
            hiBuilder).setPostFilter(// 过滤条件
            QueryBuilders.rangeQuery("salePrice").gt(priceGt).lt(priceLte)).addSort("salePrice", SortOrder.ASC).get();
        } else if (priceGt >= 0 && priceLte >= 0 && sort.equals("-1")) {
            searchResponse = client.prepareSearch(ITEM_INDEX).setTypes(ITEM_TYPE).setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setQuery(// Query
            qb).setFrom(start).setSize(size).setExplain(// 从第几个开始,显示size个数据
            true).highlighter(// 设置高亮显示
            hiBuilder).setPostFilter(// 过滤条件
            QueryBuilders.rangeQuery("salePrice").gt(priceGt).lt(priceLte)).addSort("salePrice", SortOrder.DESC).get();
        } else if ((priceGt < 0 || priceLte < 0) && sort.isEmpty()) {
            searchResponse = client.prepareSearch(ITEM_INDEX).setTypes(ITEM_TYPE).setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setQuery(// Query
            qb).setFrom(start).setSize(size).setExplain(// 从第几个开始,显示size个数据
            true).highlighter(// 设置高亮显示
            hiBuilder).get();
        } else if ((priceGt < 0 || priceLte < 0) && sort.equals("1")) {
            searchResponse = client.prepareSearch(ITEM_INDEX).setTypes(ITEM_TYPE).setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setQuery(// Query
            qb).setFrom(start).setSize(size).setExplain(// 从第几个开始,显示size个数据
            true).highlighter(// 设置高亮显示
            hiBuilder).addSort("salePrice", SortOrder.ASC).get();
        } else if ((priceGt < 0 || priceLte < 0) && sort.equals("-1")) {
            searchResponse = client.prepareSearch(ITEM_INDEX).setTypes(ITEM_TYPE).setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setQuery(// Query
            qb).setFrom(start).setSize(size).setExplain(// 从第几个开始,显示size个数据
            true).highlighter(// 设置高亮显示
            hiBuilder).addSort("salePrice", SortOrder.DESC).get();
        }
        SearchHits hits = searchResponse.getHits();
        // 返回总结果数
        searchResult.setRecordCount(hits.totalHits);
        List<SearchItem> list = new ArrayList<>();
        if (hits.totalHits > 0) {
            for (SearchHit hit : hits) {
                // 总页数
                int totalPage = (int) (hit.getScore() / size);
                if ((hit.getScore() % size) != 0) {
                    totalPage++;
                }
                // 返回结果总页数
                searchResult.setTotalPages(totalPage);
                // 设置高亮字段
                SearchItem searchItem = new Gson().fromJson(hit.getSourceAsString(), SearchItem.class);
                String productName = hit.getHighlightFields().get("productName").getFragments()[0].toString();
                searchItem.setProductName(productName);
                // 返回结果
                list.add(searchItem);
            }
        }
        searchResult.setItemList(list);
        return searchResult;
    } catch (Exception e) {
        e.printStackTrace();
        throw new XmallException("查询ES索引库出错");
    }
}
Also used : TransportClient(org.elasticsearch.client.transport.TransportClient) PreBuiltTransportClient(org.elasticsearch.transport.client.PreBuiltTransportClient) SearchHit(org.elasticsearch.search.SearchHit) TransportAddress(org.elasticsearch.common.transport.TransportAddress) ArrayList(java.util.ArrayList) Gson(com.google.gson.Gson) SearchResult(cn.exrick.manager.dto.front.SearchResult) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) XmallException(cn.exrick.common.exception.XmallException) XmallException(cn.exrick.common.exception.XmallException) SearchResponse(org.elasticsearch.action.search.SearchResponse) SearchItem(cn.exrick.manager.dto.front.SearchItem) PreBuiltTransportClient(org.elasticsearch.transport.client.PreBuiltTransportClient) SearchHits(org.elasticsearch.search.SearchHits) Settings(org.elasticsearch.common.settings.Settings) HighlightBuilder(org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder)

Aggregations

SearchHit (org.elasticsearch.search.SearchHit)166 SearchResponse (org.elasticsearch.action.search.SearchResponse)114 SearchHits (org.elasticsearch.search.SearchHits)52 ArrayList (java.util.ArrayList)31 ElasticsearchAssertions.assertSearchResponse (org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse)25 SearchRequestBuilder (org.elasticsearch.action.search.SearchRequestBuilder)22 IOException (java.io.IOException)20 Matchers.containsString (org.hamcrest.Matchers.containsString)17 IndexRequestBuilder (org.elasticsearch.action.index.IndexRequestBuilder)16 HashMap (java.util.HashMap)15 ScoreDoc (org.apache.lucene.search.ScoreDoc)14 SearchHitField (org.elasticsearch.search.SearchHitField)14 HashSet (java.util.HashSet)13 Map (java.util.Map)12 Test (org.junit.Test)12 AtomicReference (java.util.concurrent.atomic.AtomicReference)10 TopDocs (org.apache.lucene.search.TopDocs)10 Text (org.elasticsearch.common.text.Text)10 BulkRequestBuilder (org.elasticsearch.action.bulk.BulkRequestBuilder)9 BulkResponse (org.elasticsearch.action.bulk.BulkResponse)9