ElasticSearch Java api 详解_V1.0

时间:2022-04-08 01:10:44

/×××××××××××××××××××××××××××××××××××××××××/

Author:xxx0624

HomePage:http://www.cnblogs.com/xxx0624/

/×××××××××××××××××××××××××××××××××××××××××/

原英文文档:http://www.elasticsearch.org/guide/en/elasticsearch/client/java-api/index.html (各个版本的api)

这里有一个简单的使用search的官方文档:http://www.elastic.co/guide/en/elasticsearch/client/java-api/current/search.html#java-search-template

这是另外一个作者有关es api的翻译:http://blog.csdn.net/woshiyexinjie/article/details/41088705

Search部分:

查询有两种方法:query Java APIfilter Java API

首先看一个例子:

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.index.query.FilterBuilders.*;
import org.elasticsearch.index.query.QueryBuilders.*; SearchResponse response = client.prepareSearch("index1", "index2")
//设置要查询的索引(index)
.setTypes("type1", "type2")
//设置type, 这个在建立索引的时候同时设置了, 或者可以使用head工具查看
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
.setQuery(QueryBuilders.termQuery("multi", "test"))
// Query 查询之一. 对于QueryBuilders接下来会解释. 在这里"multi"是要查询的field,"test"是要查询的内容
.setFilter(FilterBuilders.rangeFilter("age").from().to())
// Filter 查询之二, FilterBuilders接下来会解释. 在这里"age"是要查询的field, 后面的数字是查询的条件范围
.setFrom().setSize().setExplain(true)
//0-60 表示显示数量
.execute()
.actionGet();

提示:以上所有参数都是可选的.

最小的查询如下所示:

// MatchAll on the whole cluster with all default options
SearchResponse response = client.prepareSearch().execute().actionGet();

1.query Java API

为了使用QueryBuilders必须先import下面的类:

import org.elasticsearch.index.query.QueryBuilders.*;

第一种:Match Query (链接内有详细解释)

QueryBuilder qb = QueryBuilders.matchQuery("name", "kimchy elasticsearch");
//name是field,kimchy elasticsearch是要查询的字符串

第二种:MultiMatch Query (链接内有详细解释)

QueryBuilder qb = QueryBuilders.multiMatchQuery(
"kimchy elasticsearch", // Text you are looking for
//kimchy elasticsearch是要查询的字符串
"user", "message" // Fields you query on
//user 和 message都是field
);

第三种: Boolean Query (链接内有详细解释)

QueryBuilder qb = QueryBuilders
.boolQuery()
.must(termQuery("content", "test1"))
.must(termQuery("content", "test4"))
.mustNot(termQuery("content", "test2"))
.should(termQuery("content", "test3"));
//content为field,test为查询内容.
//其中must表示必须满足,mustNot表示必须不满足,should表示可有可无

如果bool查询语句中不存在must,则必须至少有一个should查询,同时可以通过minimum_should_match参数来设置至少需要满足的should个数.

Boosting Query

略...

IDs Query

QueryBuilders.idsQuery().ids("1", "2");
//通过id来查询

Custom Score Query

略...

Custom Boost Factor Query

略...

Constant Score Query

略...

Disjunction Max Query

略...

Field Query

QueryBuilders.fieldQuery("name", "+kimchy -dadoonet");

// Note that you can write the same query using queryString query.
QueryBuilders.queryString("+kimchy -dadoonet").field("name");
//+表示必须有的 -表示一定没有的 name表示查询的filed

Fuzzy Like This Query * Fuzzy Like This Field Query

略....不懂.....

Fuzzy Query

QueryBuilder qb = QueryBuilders.fuzzyQuery("name", "kimzhy");
//根据提供的字符串作为前缀进行查询

Has Child Query * Has Parent

略....不懂.....

Match All Query

QueryBuilder qb = QueryBuilders.matchAllQuery();
//显示所有的记录

More Like This Query * More Like This Field Query

略...不懂......

Prefix Query

QueryBuilders.prefixQuery("brand", "heine");
//brand是field, heine是前缀查询字符串

QueryString Query

QueryBuilder qb = QueryBuilders.queryString("+kimchy -elasticsearch");

略....不懂.....

Range Query

QueryBuilder qb = QueryBuilders
.rangeQuery("price")
.from(5)
.to(10)
.includeLower(true)
.includeUpper(false);
//price是field, 数字代表范围.除了from to还有lt gt等等...

Span First Query * Span Near Query * Span Not Query * Span Or Query * Span Term Quer// Span First

QueryBuilders.spanFirstQuery(
QueryBuilders.spanTermQuery("user", "kimchy"), // Query
3 // Max End position
);
//只匹配在Field开头出现的, 数字表示从开头起的几个单词内查询, 则此查询意思是:user中的开头3个单词内,kimchy是否能查询到 // Span Near
QueryBuilders.spanNearQuery()
.clause(QueryBuilders.spanTermQuery("field","value1")) // Span Term Queries
.clause(QueryBuilders.spanTermQuery("field","value2"))
.clause(QueryBuilders.spanTermQuery("field","value3"))
.slop(12) // Slop factor
.inOrder(false)
.collectPayloads(false);
//匹配距离相近的, inOrder表示:true表示按照value1/2/3的顺序来计算距离(两个单词中间夹一个单词 距离为1). 举例: a b c d. {a,b,c}中a,c的距离为1.
//则此查询的意思是:在field中,如果value1/2/3的距离是在12以内的,那么可以查询到.反之不能. // Span Not
QueryBuilders.spanNotQuery()
.include(QueryBuilders.spanTermQuery("field","value1"))
.exclude(QueryBuilders.spanTermQuery("field","value2"));
//匹配不重叠的,即除那些两个SpanQuery相互重叠的结果
//例如有两个Document:”the quick brown fox jump over a lazy dog”和”the quick red fox jumps over the sleepy cat”
//SpanNearQuery quick_fox =new SpanNearQuery(new SpanQuery[]{quick, fox}, 1, true); //基础的SpanQuery,默认匹配2个Document
//匹配的这两个结果的中间重叠部分为:red/brown
//SpanNotQuery quick_fox_dog = new SpanNotQuery(quick_fox, dog);//因为dog不是red或者brown,所以仍为两个
//SpanNotQuery no_quick_red_fox = new SpanNotQuery(quick_fox, red); //现在只剩下brown那个doc了
//这种Query经常用于连接的时候。 // Span Or
QueryBuilders.spanOrQuery()
.clause(QueryBuilders.spanTermQuery("field","value1"))
.clause(QueryBuilders.spanTermQuery("field","value2"))
.clause(QueryBuilders.spanTermQuery("field","value3"));
//SpanQuery的合集 // Span Term
QueryBuilders.spanTermQuery("user","kimchy"); //该部分详见:http://www.coder4.com/archives/774

Term Query

略...

Terms Query

略...

Top Children Query

略...

Wildcard Query

略...

Nested Query

略...

Custom Filters Score Query

略...

Indices Query

略...

GeoShape Query

略...

2.filter Java API

附上一个自己写的小型Test, 简单易懂.

 import java.io.IOException;

 import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.FilterBuilders;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHits; import user.User; public class First_ES_Test { private Client client; public void init()
{
//ip可以在http://localhost:9200/_plugin/head/中自行查询
client = new TransportClient().addTransportAddress(new InetSocketTransportAddress("192.168.1.103", 9300));
} public void close()
{
client.close();
} /*
* create index
**/
public void createIndex() {
for (int i = 0; i < 1000; i++) {
User user = new User();
user.setId(new Long(i));
user.setName("xxx0624 " + i);
user.setAge(i % 100);
System.out.println("ok:"+i);
client.prepareIndex("users", "user").setSource(generateJson(user))
.execute().actionGet();
}
} /*
* 转换成json对象
*
* @param user
* @return json(String)
**/
private String generateJson(User user) {
String json = "";
try {
XContentBuilder contentBuilder = XContentFactory.jsonBuilder()
.startObject();
contentBuilder.field("id", user.getId() + "");
contentBuilder.field("name", user.getName());
contentBuilder.field("age", user.getAge() + "");
json = contentBuilder.endObject().string();
} catch (IOException e) {
e.printStackTrace();
}
return json;
} public void search() {
QueryBuilder qb = QueryBuilders
.boolQuery()
.must(QueryBuilders.termQuery("age", "0"))
.should(QueryBuilders.termQuery("id", "0"))
//.mustNot(QueryBuilders.termQuery("content", "test2"))
//.should(QueryBuilders.termQuery("content", "test3"))
; SearchResponse response = client.prepareSearch("users")
.setTypes("user")
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
.setQuery(qb) // Query
//.setFilter(FilterBuilders.rangeFilter("age").from(0).to(100)) // Filter
.setFrom(0).setSize(100).setExplain(true)
.execute().actionGet();
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits());
for (int i = 0; i < hits.getHits().length; i++) {
System.out.println(hits.getHits()[i].getSourceAsString());
}
} public static void main(String[] args) { First_ES_Test client = new First_ES_Test();
client.init();
client.createIndex();
client.search();
client.close(); } public void print(String output)
{
System.out.print(output);
}
public void println(String output)
{
System.out.println(output);
} }

待续...