【轉載】Elasticsearch--java操做之QueryBuilders構建搜索Query

  原文地址:https://www.cnblogs.com/pypua/articles/9459941.htmlhtml

 

package com.elasticsearch;
 
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.IndicesQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
 
/**
 * Created by lw on 14-7-15.
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 * elasticsearch以提供了一個完整的Java查詢dsl其他查詢dsl。
 * QueryBuilders工廠構建
 * API:
 * <a>http://www.elasticsearch.org/guide/en/elasticsearch/client/java-api/current/query-dsl-queries.html</a>
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 */
public class Es_QueryBuilders_DSL {
 
    /**
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * match query 單個匹配
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static QueryBuilder matchQuery() {
        return QueryBuilders.matchQuery("name", "葫蘆4032娃");
    }
 
 
    /**
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * multimatch  query
     * 建立一個匹配查詢的布爾型提供字段名稱和文本。
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static QueryBuilder multiMatchQuery() {
        //現住址和家鄉在【山西省太原市7429街道】的人
        return QueryBuilders.multiMatchQuery(
                "山西省太原市7429街道",     // Text you are looking for
                "home", "now_home"       // Fields you query on
        );
    }
 
    /**
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * boolean query and 條件組合查詢
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static QueryBuilder booleanQuery() {
 
        return QueryBuilders
                .boolQuery()
                .must(QueryBuilders.termQuery("name", "葫蘆3033娃"))
                .must(QueryBuilders.termQuery("home", "山西省太原市7967街道"))
                .mustNot(QueryBuilders.termQuery("isRealMen", false))
                .should(QueryBuilders.termQuery("now_home", "山西省太原市"));
    }
 
    /**
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * ids query
     * 構造一個只會匹配的特定數據 id 的查詢。
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static QueryBuilder idsQuery() {
        return QueryBuilders.idsQuery().ids("CHszwWRURyK08j01p0Mmug", "ojGrYKMEQCCPvh75lHJm3A");
    }
 
    /**
     * TODO NotSolved
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * constant score query
     * 另外一個查詢和查詢,包裹查詢只返回一個常數分數等於提升每一個文檔的查詢。
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static QueryBuilder constantScoreQuery() {
        /*return // Using with Filters
                QueryBuilders.constantScoreQuery(FilterBuilders.termFilter("name", "kimchy"))
                        .boost(2.0f);*/
 
        // With Queries
        return QueryBuilders.constantScoreQuery(QueryBuilders.termQuery("name", "葫蘆3033娃"))
                .boost(2.0f);
    }
 
    /**
     * TODO NotSolved
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * disjunction max query
     * 一個生成的子查詢文件產生的聯合查詢,
     * 並且每一個分數的文件具備最高得分文件的任何子查詢產生的,
     * 再加上打破平手的增長任何額外的匹配的子查詢。
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static QueryBuilder disMaxQuery() {
        return QueryBuilders.disMaxQuery()
                .add(QueryBuilders.termQuery("name", "kimchy"))          // Your queries
                .add(QueryBuilders.termQuery("name", "elasticsearch"))   // Your queries
                .boost(1.2f)
                .tieBreaker(0.7f);
    }
 
    /**
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * fuzzy query
     * 使用模糊查詢匹配文檔查詢。
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static QueryBuilder fuzzyQuery() {
        return QueryBuilders.fuzzyQuery("name", "葫蘆3582");
    }
 
    /**
     * TODO NotSolved
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * has child / has parent
     * 父或者子的文檔查詢
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static QueryBuilder hasChildQuery() {
        return // Has Child
                QueryBuilders.hasChildQuery("blog_tag",
                        QueryBuilders.termQuery("tag", "something"));
 
        // Has Parent
        /*return QueryBuilders.hasParentQuery("blog",
                QueryBuilders.termQuery("tag","something"));*/
    }
 
    /**
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * matchall query
     * 查詢匹配全部文件。
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static QueryBuilder matchAllQuery() {
        return QueryBuilders.matchAllQuery();
    }
 
    /**
     * TODO NotSolved
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * more like this (field) query (mlt and mlt_field)
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static QueryBuilder moreLikeThisQuery() {
        // mlt Query
        QueryBuilders.moreLikeThisQuery("home", "now_home") // Fields
                .likeText("山西省太原市7429街道")                 // Text
                .minTermFreq(1)                                 // Ignore Threshold
                .maxQueryTerms(12);                             // Max num of Terms
        // in generated queries
 
        // mlt_field Query
        return QueryBuilders.moreLikeThisFieldQuery("home")              // Only on single field
                .likeText("山西省太原市7429街道")
                .minTermFreq(1)
                .maxQueryTerms(12);
    }
 
    /**
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * prefix query
     * 包含與查詢相匹配的文檔指定的前綴。
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static QueryBuilder prefixQuery() {
        return QueryBuilders.prefixQuery("name", "葫蘆31");
    }
 
    /**
     * TODO NotSolved
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * querystring query
     *   查詢解析查詢字符串,並運行它。有兩種模式,這種經營。
     * 第一,當沒有添加字段(使用{ @link QueryStringQueryBuilder #字段(String)},將運行查詢一次,非字段前綴
     *   將使用{ @link QueryStringQueryBuilder # defaultField(字符串)}。
     * 第二,當一個或多個字段
     *   (使用{ @link QueryStringQueryBuilder #字段(字符串)}),將運行提供的解析查詢字段,並結合
     *   他們使用DisMax或者一個普通的布爾查詢(參見{ @link QueryStringQueryBuilder # useDisMax(布爾)})。
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static QueryBuilder queryString() {
        return QueryBuilders.queryString("+kimchy -elasticsearch");
    }
 
    /**
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * range query
     * 查詢相匹配的文檔在一個範圍。
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static QueryBuilder rangeQuery() {
        return QueryBuilders
                .rangeQuery("name")
                .from("葫蘆1000娃")
                .to("葫蘆3000娃")
                .includeLower(true)     //包括下界
                .includeUpper(false); //包括上界
    }
 
    /**
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * span queries (first, near, not, or, term)
     * 跨度查詢
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static QueryBuilder spanQueries() {
        // Span First
        QueryBuilders.spanFirstQuery(
                QueryBuilders.spanTermQuery("name", "葫蘆580娃"),  // Query
                                            // Max查詢範圍的結束位置
        );
 
        // Span Near TODO NotSolved
        QueryBuilders.spanNearQuery()
                .clause(QueryBuilders.spanTermQuery("name", "葫蘆580娃")) // Span Term Queries
                .clause(QueryBuilders.spanTermQuery("name", "葫蘆3812娃"))
                .clause(QueryBuilders.spanTermQuery("name", "葫蘆7139娃"))
                .slop(30000)                                               // Slop factor
                .inOrder(false)
                .collectPayloads(false);
 
        // Span Not TODO NotSolved
        QueryBuilders.spanNotQuery()
                .include(QueryBuilders.spanTermQuery("name", "葫蘆580娃"))
                .exclude(QueryBuilders.spanTermQuery("home", "山西省太原市2552街道"));
 
        // Span Or TODO NotSolved
        return QueryBuilders.spanOrQuery()
                .clause(QueryBuilders.spanTermQuery("name", "葫蘆580娃"))
                .clause(QueryBuilders.spanTermQuery("name", "葫蘆3812娃"))
                .clause(QueryBuilders.spanTermQuery("name", "葫蘆7139娃"));
 
        // Span Term
        //return QueryBuilders.spanTermQuery("name", "葫蘆580娃");
    }
 
 
    /**
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * term query
     * 一個查詢相匹配的文件包含一個術語。。
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static QueryBuilder termQuery() {
        return QueryBuilders.termQuery("name", "葫蘆580娃");
    }
 
 
    /**
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * terms query
     * 一個查詢相匹配的多個value
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static QueryBuilder termsQuery() {
        return QueryBuilders.termsQuery("name", // field
                "葫蘆580娃", "葫蘆3812娃")                 // values
                .minimumMatch(1);               // 設置最小數量的匹配提供了條件。默認爲1。
    }
 
    /**
     * TODO NotSolved
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * top children  query
     * 構建了一種新的評分的子查詢,與子類型和運行在子文檔查詢。這個查詢的結果是,那些子父文檔文件匹配。
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static QueryBuilder topChildrenQuery() {
        return QueryBuilders.topChildrenQuery(
                "blog_tag",                                 // field
                QueryBuilders.termQuery("name", "葫蘆3812娃") // Query
        )
                .score("max")                               // max, sum or avg
                .factor(5)
                .incrementalFactor(2);
    }
 
    /**
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * wildcard query
     *   實現了通配符搜索查詢。支持通配符* < /tt>,<tt>
     *   匹配任何字符序列(包括空),<tt> ? < /tt>,
     *   匹配任何單個的字符。注意該查詢能夠緩慢,由於它
     *   許多方面須要遍歷。爲了防止WildcardQueries極其緩慢。
     *   一個通配符詞不該該從一個通配符* < /tt>或<tt>
     *   < /tt> <tt> ?。
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static QueryBuilder wildcardQuery() {
        return QueryBuilders.wildcardQuery("name", "葫蘆*2娃");
    }
 
    /**
     * TODO NotSolved
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * nested query
     * 嵌套查詢
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static QueryBuilder nestedQuery() {
        return QueryBuilders.nestedQuery("location",               // Path
                QueryBuilders.boolQuery()                      // Your query
                        .must(QueryBuilders.matchQuery("location.lat", 0.962590433140581))
                        .must(QueryBuilders.rangeQuery("location.lon").lt(0.00000000000000000003))
        )
                .scoreMode("total");                  // max, total, avg or none
    }
 
    /**
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * indices query
     * 索引查詢
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    protected static IndicesQueryBuilder indicesQuery() {
        // Using another query when no match for the main one
        QueryBuilders.indicesQuery(
                QueryBuilders.termQuery("name", "葫蘆3812娃"),
                Es_Utils.INDEX_DEMO_01, "index2"
        )       //設置查詢索引上執行時使用不匹配指數
                .noMatchQuery(QueryBuilders.termQuery("age", "葫蘆3812娃"));
 
 
        // Using all (match all) or none (match no documents)
        return QueryBuilders.indicesQuery(
                QueryBuilders.termQuery("name", "葫蘆3812娃"),
                Es_Utils.INDEX_DEMO_01, "index2"
        )      // 設置不匹配查詢,能夠是 all 或者 none
                .noMatchQuery("none");
    }
 
 
 
 
    public static void main(String[] args) {
        Es_Utils.startupClient();
        try {
            searchTest(indicesQuery());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            Es_Utils.shutDownClient();
        }
    }
 
    private static void searchTest(QueryBuilder queryBuilder) {
        //預準備執行搜索
        Es_Utils.client.prepareSearch(Es_Utils.INDEX_DEMO_01)
                .setTypes(Es_Utils.INDEX_DEMO_01_MAPPING)
                .setQuery(queryBuilder)
                .setFrom(0).setSize(20).setExplain(true)
                .execute()
                        //註冊監聽事件
                .addListener(new ActionListener<SearchResponse>() {
                    @Override
                    public void onResponse(SearchResponse searchResponse) {
                        Es_Utils.writeSearchResponse(searchResponse);
                    }
 
                    @Override
                    public void onFailure(Throwable e) {
 
                    }
                });
    }
}
相關文章
相關標籤/搜索