Source: http://blog.csdn.net/xiaohulunb/article/details/37877435
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 to provide A complete Java query dsl is given for the rest of the query dsl.
* QueryBuilders factory builds
* API:
* <a>http://www.elasticsearch.org/gui ... ries.html</a>
* ~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
public class Es_QueryBuilders_DSL {
/**
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~
* match query single match
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~
*/
protected static QueryBuilder matchQuery() {
return QueryBuilders.matchQuery("name", "Hulu 4032 baby");
}
/* *
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~
* multimatch query
* Creates a boolean match query providing field names and text.
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~
*/
protected static QueryBuilder multiMatchQuery() {
//People whose current address and hometown are in [7429 Street, Taiyuan City, Shanxi Province]
return QueryBuilders.multiMatchQuery(
"7429 Street, Taiyuan City, Shanxi Province", // Text you are looking for
"home", "now_home" // Fields you query on
);
}
/**
* ~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* boolean query and condition Combination query
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~
*/
protected static QueryBuilder booleanQuery() {
return QueryBuilders
.boolQuery()
.must(QueryBuilders.termQuery("name", "Hulu 3033wa"))
.must(QueryBuilders.termQuery("home" , "7967 Street, Taiyuan City, Shanxi Province" ))
.mustNot(QueryBuilders.termQuery("isRealMen", false))
.should(QueryBuilders.termQuery("now_home", "Taiyuan, Shanxi"));
}
/**
* ~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* ids query
* Construct an only A query that will match a specific data id.
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~
*/
protected static QueryBuilder idsQuery() {
return QueryBuilders.idsQuery().ids("CHszwWRURyK08j01p0Mmug", "ojGrYKMEQCCPvh75lHJm3A");
}
/**
* TODO NotSolved
* ~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* constant score query
* Another query and query that wraps the query only returns a constant score equal to the query that improves each document.
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~
*/
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", "Hulu 3033wa"))
.boost(2.0f);
}
/**
* TODO NotSolved
* ~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* disjunction max query
* A generated subquery file yields the union query,
* and each scoring file has the highest scoring file any subquery yields,
* plus any additional matching subqueries that break the tie by adding.
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~
*/
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
* Use fuzzy query to match document query.
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~
*/
protected static QueryBuilder fuzzyQuery() {
return QueryBuilders.fuzzyQuery("name", "Hulu 3582");
}
/**
* TODO NotSolved
* ~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* has child / has parent
* parent or Sub-document query
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~
*/
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
* Contains the specified prefix for documents that match the query.
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~
*/
protected static QueryBuilder prefixQuery() {
return QueryBuilders.prefixQuery("name", "Hulu31");
}
/**
* TODO NotSolved
* ~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* querystring query
* Query parsing query string , and run it. There are two modes of this kind of operation.
* First, when no fields are added (using { @link QueryStringQueryBuilder #field(String)}, the query will be run once, non-field prefixes
* will use { @link QueryStringQueryBuilder #defaultField(String)}.
* Second, when a or more fields
* (using { @link QueryStringQueryBuilder #fields(string)}), will run the provided parsed query fields, and combine
them with DisMax or a plain boolean query (see { @link QueryStringQueryBuilder # useDisMax(boolean)}).
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~
*/
protected static QueryBuilder queryString() {
return QueryBuilders. queryString("+kimchy -elasticsearch");
}
/**
* ~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* range query
* Query matching documents in a range.
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~
*/
protected static QueryBuilder rangeQuery() {
return QueryBuilders
.rangeQuery("name")
.from("Hulu 1000 baby")
.to("Hulu 3000 baby")
.includeLower(true) //include lower
bound.includeUpper(false); //include upper bound
}
/**
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~
* span queries (first, near, not, or, term)
*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
protected static QueryBuilder spanQueries() {
// Span First
QueryBuilders.spanFirstQuery(
QueryBuilders.spanTermQuery("name" , "Hulu 580 baby"), // Query
30000 // The end of the Max query range
);
// Span Near TODO NotSolved
QueryBuilders.spanNearQuery()
.clause(QueryBuilders.spanTermQuery("name", "Hulu 580wa")) // Span Term Queries
.clause(QueryBuilders. spanTermQuery("name", "Hulu 3812 baby"))
.clause(QueryBuilders.spanTermQuery("name", "Hulu 7139 baby"))
.slop(30000) // Slop factor
.inOrder(false)
.collectPayloads(false) ;
// Span Not TODO NotSolved
QueryBuilders.spanNotQuery()
} /** * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~ * term query * A query matches a document containing a term. .
// Set the minimum number of matches provided conditions. Defaults to 1. } /**
* TODO NotSolved
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~
* top children query
* Constructs a new scoring subquery, with subtypes and queries that run on subdocuments. As a result of this query, those child-parent document files match.
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~
*/
protected static QueryBuilder topChildrenQuery() {
return QueryBuilders.topChildrenQuery(
"blog_tag", // field
QueryBuilders.termQuery("name", "Hulu 3812wa") // Query
)
.score("max" ) // max, sum or avg
.factor(5)
.incrementalFactor(2);
/**
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~
* wildcard query
* Implements wildcard search query. Wildcards are supported * < /tt>, <tt>
* matches any sequence of characters (including null), <tt> ? </tt>,
* matches any single character. Note that this query can be slow because it
*many needs to be traversed. To prevent WildcardQueries from being extremely slow.
* A wildcard word should not start from a wildcard *</tt> or <tt>
*</tt> <tt>?.
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~
*/
protected static QueryBuilder wildcardQuery() {
return QueryBuilders.wildcardQuery("name", "Hulu*2 baby");
* 嵌套查询
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
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
* Index query
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~
*/
protected static IndicesQueryBuilder indicesQuery() {
// Using another query when no match for the main one
QueryBuilders.indicesQuery(
QueryBuilders.termQuery("name", "Hulu 3812wa"),
Es_Utils. INDEX_DEMO_01, "index2"
) // Using all (match all) or none (match no
)
// Using all (match all) or none (match no) documents)
return QueryBuilders.indicesQuery(
QueryBuilders.termQuery("name", "Hulu 3812wa"),
Es_Utils.INDEX_DEMO_01, "index2"
) // Set mismatch query, can be all or 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) {
//Prepare to execute search
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) {
}
});
}
}
elasticsearch java operation
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=326458616&siteId=291194637
Ranking