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

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) { }
});
}
}

  

【转载】Elasticsearch--java操作之QueryBuilders构建搜索Query的更多相关文章

  1. elasticsearch------java操作之QueryBuilders构建搜索Query

    版权声明:本文为非原创文章,出处:http://blog.csdn.net/xiaohulunb/article/details/37877435. elasticsearch 分布式搜索系列专栏:h ...

  2. [转载]Elasticsearch Java API总汇

    from: http://blog.csdn.net/changong28/article/details/38445805#comments 3.1 集群的连接 3.1.1 作为Elasticsea ...

  3. [转载]使用Java操作Mongodb

    HelloWorld程序 学习任何程序的第一步,都是编写HelloWorld程序,我们也不例外,看下如何通过Java编写一个HelloWorld的程序. 首先,要通过Java操作Mongodb,必须先 ...

  4. elasticsearch__5__java操作之FilterBuilders构建过滤器Query

    FilterBuilders构建过滤器Query 代码如下: package com.elasticsearch; import org.elasticsearch.action.ActionList ...

  5. elasticsearch聚合操作——本质就是针对搜索后的结果使用桶bucket(允许嵌套)进行group by,统计下分组结果,包括min/max/avg

    分析 Elasticsearch有一个功能叫做聚合(aggregations),它允许你在数据上生成复杂的分析统计.它很像SQL中的GROUP BY但是功能更强大. 举个例子,让我们找到所有职员中最大 ...

  6. Elasticsearch java api 基本搜索部分详解

    文档是结合几个博客整理出来的,内容大部分为转载内容.在使用过程中,对一些疑问点进行了整理与解析. Elasticsearch java api 基本搜索部分详解 ElasticSearch 常用的查询 ...

  7. 使用Java操作Elasticsearch(Elasticsearch的java api使用)

    1.Elasticsearch是基于Lucene开发的一个分布式全文检索框架,向Elasticsearch中存储和从Elasticsearch中查询,格式是json. 索引index,相当于数据库中的 ...

  8. Elasticsearch笔记五之java操作es

    Java操作es集群步骤1:配置集群对象信息:2:创建客户端:3:查看集群信息 1:集群名称 默认集群名为elasticsearch,如果集群名称和指定的不一致则在使用节点资源时会报错. 2:嗅探功能 ...

  9. 2 - 基于ELK的ElasticSearch 7.8.x技术整理 - java操作篇 - 更新完毕

    3.java操作ES篇 3.1.摸索java链接ES的流程 自行创建一个maven项目 3.1.1.依赖管理 点击查看代码 <properties> <ES-version>7 ...

随机推荐

  1. 用Matlab的.m脚本文件处理实验室数据

    找到相应的文件 findfile %1 打开文件夹 %2 拷贝第一个文件 %3 关闭当前文件,再次拷贝新的文件,直到文件末尾结束 clc clear DST_PATH_t = 'C:\Users\Ma ...

  2. 阿里腾讯校招Java面试题总结及答案

    阿里校招java面试题汇总 1.HashMap和HashTable的区别,及其实现原理. Hashtable继承自Dictionary类,而HashMap是Java1.2引进的,继承自Abstract ...

  3. Ehcahe独立使用

    <?xml version="1.0" encoding="utf-8"?><ehcache xmlns:xsi="http://w ...

  4. 人生苦短_我用Python_Try_Exception异常捕捉_007

    # coding=utf-8 ''' request+try__异常处理 ''' import requests class HttpRequests: def __init__(self, url, ...

  5. "less is more",用"less”命令查看linux文本文件

    less filename:可以方便地查看文本文件 当一条命令的输出结果较长的时候,可以通过管道传给less命令便于浏览,比如ls -al | less.

  6. js 最短代码生成随机数(字符串、id)

    以生成8位字符串为例 Math.random().toString(36).substr(-8)

  7. boost Shared Memory

    Shared Memory Shared memory is typically the fastest form of interprocess communicatioin. It provide ...

  8. Java Web学习总结(7)JSP(一)

    一,JSP基础语法 1,JSP模板元素 JSP页面中的HTML内容称之为JSP模版元素. JSP模版元素定义了网页的基本骨架,即定义了页面的结构和外观. 2,JSP脚本片段 JSP脚本片断(scrip ...

  9. sql判断中文、数字、英文

    IF OBJECT_ID('DBO.GET_NUMBER2') IS NOT NULL DROP FUNCTION DBO.GET_NUMBER2 GO )) ) AS BEGIN BEGIN ,'' ...

  10. loadrunner(预测系统行为和性能的负载测试工具)

    LoadRunner,是一种预测系统行为和性能的负载测试工具.通过以模拟上千万用户实施并发负载及实时性能监测的方式来确认和查找问题,LoadRunner能够对整个企业架构进行测试.企业使用LoadRu ...