elasticsearch__5__자바 작업 의 FilterBuilders 필터 구축 Query

13411 단어 Elasticsearch
elasticsearch 분산 검색 시리즈 칼럼:http://blog.csdn.net/xiaohulunb/article/category/2399789
코드 GitHub 주소: 클릭 하여 링크 열기
필터 빌 더 구축 필터 Query
package com.elasticsearch;

import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.geo.GeoDistance;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.*;

/**
 * Created by lw on 14-7-16.
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 * elasticsearch         Java  dsl    dsl。
 * FilterBuilders    
 * API:
 * http://www.elasticsearch.org/guide/en/elasticsearch/client/java-api/current/query-dsl-filters.html
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 */
public class Es_FilterBuilders_DSL {


    /**
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * and Filter
     *                      。
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static FilterBuilder andFilter() {
        return FilterBuilders.andFilter(
                FilterBuilders.rangeFilter("age").from(1).to(1000),
                FilterBuilders.prefixFilter("name", "  1493")
        );
    }

    /**
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * bool Filter
     *                      。
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static FilterBuilder boolFilter() {
        return FilterBuilders.boolFilter()
                .must(FilterBuilders.termFilter("name", "  1493 "))
                .mustNot(FilterBuilders.rangeFilter("age").from(1000).to(3000))
                .should(FilterBuilders.termFilter("home", "      7077  "));
    }

    /**
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * exists filter
     *                 。
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static FilterBuilder existsFilter() {
        return FilterBuilders.existsFilter("home");
    }

    /**
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * ids filter
     *       id     doc/    。
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static FilterBuilder idsFilter() {
        return FilterBuilders.idsFilter(Es_Utils.INDEX_DEMO_01_MAPPING, "type2")
                .addIds("SNt0KdNbRdKmXJVaXfNxEA", "UDKtO4o9TgmDHIT4bk_OWw", "jkAZoHe9RWyjxyOnBCTdrw");

        // Type is optional
        //FilterBuilders.idsFilter().addIds("1", "4", "100");
    }

    /**
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * limit filter
     *      ,            (  shard * 2 )。
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static FilterBuilder limitFilter() {
        return FilterBuilders.limitFilter(2);//    shard*2    
    }

    /**
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * type filter
     *   type
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static FilterBuilder typeFilter() {
        return FilterBuilders.typeFilter(Es_Utils.INDEX_DEMO_01_MAPPING);
    }

    /**
     * TODO NotSolved
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * geo bounding box filter
     *                          / 
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static FilterBuilder geoBoundingBoxFilter() {
        return FilterBuilders.geoBoundingBoxFilter("pin.location")
                .topLeft(40.73, -74.1)
                .bottomRight(40.717, -73.99);
    }


    /**
     * TODO NotSolved
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * geodistance filter
     *                            / 。
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static FilterBuilder geoDistanceFilter() {
        return FilterBuilders.geoDistanceFilter("pin.location")
                .point(40, -70)
                .distance(200, DistanceUnit.KILOMETERS)
                .optimizeBbox("memory")                    // Can be also "indexed" or "none"
                .geoDistance(GeoDistance.ARC);            // Or GeoDistance.PLANE
    }

    /**
     * TODO NotSolved
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * geo distance range filter
     *                            / 。
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static FilterBuilder geoDistanceRangeFilter() {
        return FilterBuilders.geoDistanceRangeFilter("pin.location")
                .point(40, -70)
                .from("200km")
                .to("400km")
                .includeLower(true)
                .includeUpper(false)
                .optimizeBbox("memory")                    // Can be also "indexed" or "none"
                .geoDistance(GeoDistance.ARC);            // Or GeoDistance.PLANE
    }

    /**
     * TODO NotSolved
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * geo polygon filter
     *                     / 。
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static FilterBuilder geoPolygonFilter() {
        return FilterBuilders.geoPolygonFilter("pin.location")
                .addPoint(40, -70)
                .addPoint(30, -80)
                .addPoint(20, -90);
    }


    /**
     * TODO NotSolved
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * has child / has parent filters
     *         ,         、       * *  。
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static FilterBuilder hasChildFilter() {
        // Has Child
        FilterBuilders.hasChildFilter("blog_tag",
                QueryBuilders.termQuery("tag", "something"));

        // Has Parent
        return FilterBuilders.hasParentFilter("blog",
                QueryBuilders.termQuery("tag", "something"));
    }

    /**
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * match all filter
     *            。
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static FilterBuilder matchAllFilter() {
        return FilterBuilders.matchAllFilter();
    }

    /**
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * missing filter
     *                  。
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static FilterBuilder missingFilter() {
        return FilterBuilders.missingFilter("name")
                .existence(true)
                .nullValue(true);
    }

    /**
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * not filter
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static FilterBuilder notFilter() {
        return FilterBuilders.notFilter(
                FilterBuilders.rangeFilter("age").from(1000).to(2000));
    }

    /**
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * or filter
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static FilterBuilder orFilter() {
        return FilterBuilders.orFilter(
                FilterBuilders.termFilter("name", "  1493 "),
                FilterBuilders.termFilter("name", "  5083 ")
        );
    }

    /**
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * prefix filter
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static FilterBuilder prefixFilter() {
        return FilterBuilders.prefixFilter("name", "  5083");
    }

    /**
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * query filter
     *      ,       。
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static FilterBuilder queryFilter() {
        return FilterBuilders.queryFilter(
                QueryBuilders.queryString("name")
        );
    }

    /**
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * range filter
     *    ,              。
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static FilterBuilder rangeFilter() {
        FilterBuilders.rangeFilter("age")
                .from(1000)
                .to(2000)
                .includeLower(true)
                .includeUpper(false);

        // A simplified form using gte, gt, lt or lte
        return FilterBuilders.rangeFilter("age")
                .gte(1000)
                .lt(2000);
    }

    /**
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * script filter
     *           。
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static FilterBuilder scriptFilter() {
        return FilterBuilders.scriptFilter(
                "doc['age'].value > param1"
        ).addParam("param1", 1000);
    }

    /**
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * term filter
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static FilterBuilder termFilter() {
        return FilterBuilders.termFilter("name", "  5083 ");
    }

    /**
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * terms filter
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * The execution option now has the following options :
     * 
     * plain
     * The default. Works as today. Iterates over all the terms, building a bit set matching it, and filtering. The total filter is cached.
     * 
     * fielddata
     * Generates a terms filters that uses the fielddata cache to compare terms.
     * This execution mode is great to use when filtering on a field that is already loaded into the fielddata cache from faceting, sorting, or index warmers.
     * When filtering on a large number of terms, this execution can be considerably faster than the other modes.
     * The total filter is not cached unless explicitly configured to do so.
     * 
     * bool
     * Generates a term filter (which is cached) for each term, and wraps those in a bool filter.
     * The bool filter itself is not cached as it can operate very quickly on the cached term filters.
     * 
     * and
     * Generates a term filter (which is cached) for each term, and wraps those in an and filter.
     * The and filter itself is not cached.
     * 
     * or
     * Generates a term filter (which is cached) for each term, and wraps those in an or filter.
     * The or filter itself is not cached. Generally, the bool execution mode should be preferred.
     */
    protected static FilterBuilder termsFilter() {
        return FilterBuilders.termsFilter("name", "  5083 ", "  3582 ")
                .execution("plain");     //      Cane be either "plain", "bool" "and". Defaults to "plain".
    }

    /**
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * nested filter
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static FilterBuilder nestedFilter() {
        return FilterBuilders.nestedFilter("obj1",
                QueryBuilders.boolQuery()
                        .must(QueryBuilders.matchQuery("obj1.name", "blue"))
                        .must(QueryBuilders.rangeQuery("obj1.count").gt(5))
        );
    }

    /**
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * caching
     *       
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static FilterBuilder cache() {
        return FilterBuilders.andFilter(
                FilterBuilders.rangeFilter("age").from(1000).to(9000),
                FilterBuilders.prefixFilter("name", "  3582")
        )
                .cache(true);//  false
    }


    public static void main(String[] args) {
        Es_Utils.startupClient();
        try {
            searchTest(cache());

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            Es_Utils.shutDownClient();
        }
    }

    private static void searchTest(FilterBuilder filterBuilder) {
        //       
        Es_Utils.client.prepareSearch(Es_Utils.INDEX_DEMO_01)
                .setTypes(Es_Utils.INDEX_DEMO_01_MAPPING)
                .setPostFilter(filterBuilder)
                .setFrom(0).setSize(20).setExplain(true)
                .execute()
                        //      
                .addListener(new ActionListener() {
                    @Override
                    public void onResponse(SearchResponse searchResponse) {
                        Es_Utils.writeSearchResponse(searchResponse);
                    }

                    @Override
                    public void onFailure(Throwable e) {

                    }
                });
    }
}

좋은 웹페이지 즐겨찾기