一、引入依赖
<!--Elasticsearch client-->
<!-- https://mvnrepository.com/artifact/org.elasticsearch.client/transport -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>6.2.3</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>6.2.3</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.plugin</groupId>
<artifactId>transport-netty4-client</artifactId>
<version>6.2.3</version>
</dependency>
二、上代码
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Test; import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map; public class ElasticsearchTest {
@Test
public void queryTest() throws UnknownHostException {
//集群设置
//Settings settings = Settings.builder().put("cluster.name", "myClusterName").build(); //设置ES实例的名称
Settings settings = Settings.builder().put("client.transport.sniff", false).build();
TransportClient client = new PreBuiltTransportClient(settings);
client.addTransportAddress(new TransportAddress(InetAddress.getByName("172.16.4.141"), 9300));
SearchRequestBuilder searchBuilder = client.prepareSearch("logstash-*").setSize(10).setFrom(0);
searchBuilder.addSort("@timestamp", SortOrder.DESC);
searchBuilder.setQuery(QueryBuilders.multiMatchQuery("Success", "logger_name", "message", "host"));
searchBuilder.setQuery(QueryBuilders.matchPhraseQuery("level", "INFO"));
searchBuilder.setQuery(QueryBuilders.matchPhraseQuery("appName", "backend-sync"));
searchBuilder.setQuery(QueryBuilders.rangeQuery("@timestamp").from("2018-12-04T10:50:19.379Z").to("2018-12-04T10:58:19.379Z")); SearchResponse response = searchBuilder.execute().actionGet();
System.out.println("TotalHits:" + response.getHits().getTotalHits());
System.out.println("TotalHits Return:" + response.getHits().getHits().length);
System.out.println("MaxScore:" + response.getHits().getMaxScore());
for (SearchHit hit : response.getHits()) {
Map<String, Object> map = hit.getSourceAsMap();
if (map != null) {
System.out.println(hit.getSourceAsString());
}
}
client.close();
}
}
三、查询
说明:上文中,按timestamp倒序排列,并搜索日志中包含"Success"、Level级别为"INFO"的、AppName为"backend-sync",并取得查询到的条数。
四、说明
matchPhraseQuery和matchQuery等的区别,在使用matchQuery等时,在执行查询时,搜索的词会被分词器分词,而使用matchPhraseQuery时,不会被分词器分词,而是直接以一个短语的形式查询,而如果你在创建索引所使用的field的value中没有这么一个短语(顺序无差,且连接在一起),那么将查询不出任何结果。
五、上图