Elasticsearch Java API—多條件查詢(must)

來源:互聯網
上載者:User

標籤:soc   comm   oid   arraylist   iba   ping   catch   getc   demo   

多條件設定
//多條件設定MatchPhraseQueryBuilder mpq1 = QueryBuilders                .matchPhraseQuery("pointid","W3.UNIT1.10LBG01CP301");MatchPhraseQueryBuilder mpq2 = QueryBuilders                .matchPhraseQuery("inputtime","2016-07-21 00:00:01");QueryBuilder qb2 = QueryBuilders.boolQuery().must(mpq1).must(mpq2);

Demo:

package com.zx.znyd.es; import java.io.IOException;import java.util.Date;import java.util.HashMap;import java.util.Map;import org.apache.commons.lang.StringUtils;import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;import org.elasticsearch.action.get.GetResponse;import org.elasticsearch.action.index.IndexRequest;import org.elasticsearch.action.search.SearchResponse;import org.elasticsearch.action.search.SearchType;import org.elasticsearch.client.Client;import org.elasticsearch.client.Requests;import org.elasticsearch.client.transport.TransportClient;import org.elasticsearch.common.mustache.Mustache;import org.elasticsearch.common.settings.ImmutableSettings;import org.elasticsearch.common.settings.Settings;import org.elasticsearch.common.transport.InetSocketTransportAddress;import org.elasticsearch.common.transport.TransportAddress;import org.elasticsearch.common.xcontent.XContentBuilder;import org.elasticsearch.common.xcontent.XContentFactory;import org.elasticsearch.index.query.MatchQueryBuilder.Operator;import org.elasticsearch.index.query.QueryBuilders;import org.elasticsearch.search.SearchHit;import org.elasticsearch.search.SearchHits;import org.elasticsearch.search.sort.SortOrder;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.alibaba.fastjson.JSONObject;import com.zx.znyd.common.MD5;import com.zx.znyd.common.SpringContextUtil;import com.zx.znyd.dao.AutoReplyDao;import com.zx.znyd.data.model.AutoReply;import com.zx.znyd.data.model.LogIndex;import com.zx.znyd.service.AutoReplyDeployService; @RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = "classpath:applicationContext.xml")public class TestES {     @Autowired    @Qualifier("esClient")    private Client client;         @Test     public void testSearch()     {         String index="index_log_daily";        String type="uq_log";        String uquestion = "139";        String province = "江蘇";        SearchResponse searchResponse = client.prepareSearch(index)                 .setTypes(type)                 .setQuery(QueryBuilders.matchAllQuery()) //查詢所有                .setQuery(QueryBuilders.boolQuery()                .must(QueryBuilders.matchQuery("uquestion", uquestion))//查詢uquestion為139的                .must(QueryBuilders.matchQuery("province", province)))//查詢省份為江蘇的                       .setSearchType(SearchType.QUERY_THEN_FETCH)                 .setFrom(0).setSize(10)//分頁                 //.addSort("age", SortOrder.DESC)//排序                 .get();                    SearchHits hits = searchResponse.getHits();         long total = hits.getTotalHits();         System.out.println(total);         SearchHit[] searchHits = hits.hits();         for(SearchHit s : searchHits)         {             System.out.println(s.getSourceAsString());            String []logindex=s.getSourceAsString().split(",");                     }     } }

  貼下My Code:

       /** * 錯誤記錄檔統計 */@Overridepublic List<TomcatModel> errorTomcatRequest(Page page, String index,String startDate, String endDate) {TransportClient client = getClient();if (index.isEmpty() == true) {return null;}DateInterval dateInterval = RegexUtil.getDateInterval(new DateInterval(startDate,endDate),"yyyyMMdd");List<TomcatModel> list = new ArrayList<TomcatModel>();try {SearchResponse response = client.prepareSearch(index).setTypes(getIndexType()).setFrom(page.getStart()).setSize(page.getLength()).setQuery(QueryBuilders.boolQuery().must(QueryBuilders.regexpQuery("response", "[4-6][0-9][0-9]")).must(QueryBuilders.rangeQuery("@timestamp").format("yyyyMMdd").from(dateInterval.getStartDate()).to(dateInterval.getEndDate()))).addSort("@timestamp", SortOrder.ASC).execute().actionGet();SearchHits myhits = response.getHits();page.setRecordsFiltered((int) myhits.getTotalHits());page.setRecordsTotal((int) myhits.getTotalHits());int i = 1;for (SearchHit hit : myhits.getHits()) {TomcatModel tomcat = new TomcatModel();Map<String, Object> map = hit.getSource();tomcat.setClientip((String) map.get("clientip"));tomcat.setResponse((String) map.get("response"));tomcat.setMessage((String) map.get("message"));tomcat.setType((String) map.get("verb"));tomcat.setTimestamp((String) map.get("timestamp"));tomcat.setRowId(i);list.add(tomcat);i++;}} catch (IndexNotFoundException e) {System.err.println("此索引不存在!");}catch (Exception e) {e.printStackTrace();}return list;}

  


 

Elasticsearch Java API—多條件查詢(must)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.