ES的模糊查询,在多个索引或者单个索引,全局查询

ES的模糊查询(ES查询),在多个索引或者单个索引,全局查询

官方的简单查询如下图:
可以在new SearchRequest()里的()中加入索引,就会根据下图的代码查询索引下所有数据。
ES查询
或者可以指定多个索引进行查询:
因为FieldCapabilitiesRequest继承的是SearchRequest,所以只需要直接像FieldCapabilitiesRequest一样把fields()和indices()添加到SearchRequest后面就行了。可以指定多个field和index
ES查询
查询某个索引下的所有数据:
在第一张图上的searchSourceBuilder.query()中添加参数如下两个:

// 我用的7.7es会自动中文分词
QueryBuilders.multiMatchQuery("我是老八");
//我用的7.7es会自动中文分词
// new MultiMatchQueryBuilder("我是宋三")也行
new MultiMatchQueryBuilder("我是宋三","user","message");

我自己的测试代码如下:(下面的可以不看,我自己存下来的方便自己查看)

package com.rg1b;

import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;

import java.net.InetAddress;
import java.sql.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;

public class Ceshi {

    public static void createAndupdate(String[] args) throws  Exception{
        String sql = "select * from BLOG_USER LIMIT 100 ";
        String driver = "com.mysql.cj.jdbc.Driver";
        String url = "jdbc:mysql://ip:3306/数据库?serverTimezone=UTC&autoReconnect=true";
        String user = "账号";
        String pwd = "密码";
        Class.forName(driver);
        Connection conn = DriverManager.getConnection(url, user, pwd);
        Statement statement = conn.createStatement();
        ResultSet rs = statement.executeQuery(sql);
        String username = "";
        String password = "";
        String Uname = "";
        String ID = "";
        String phone = "";
        String mailbox = "";
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http")
                ));
        Map<String, String> jsonMap = new HashMap<>();
        //批量处理类
        BulkRequest bulkrequest = new BulkRequest();
        //批量从mysql中引到ES
        while(rs.next()){
            username = rs.getString("username");
            password = rs.getString("password");
            Uname = rs.getString("Uname");
            ID = rs.getString("ID");
            phone = rs.getString("phone");
            mailbox = rs.getString("mailbox");
            jsonMap.put("username", username);
            jsonMap.put("password", password);
            jsonMap.put("Uname", Uname);
            jsonMap.put("ID", ID);
            jsonMap.put("phone",phone);
            jsonMap.put("mailbox", mailbox);
            IndexRequest request = new IndexRequest("blog_user")
                    .id(ID).source(jsonMap);
            bulkrequest.add(request);
        }



		
        BulkResponse bulkResponse = client.bulk(bulkrequest, RequestOptions.DEFAULT);
        System.out.println(bulkResponse.toString());
    }

	//查询
    public static void select(String[] args) throws  Exception{
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http")
                ));
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices("posts");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//        String[] includeFields = new String[] {"user"};
//        String[] excludeFields = new String[] {""};
//        searchSourceBuilder.fetchSource(includeFields, excludeFields);
//        searchSourceBuilder.query(QueryBuilders.multiMatchQuery("我是老八"));
        searchSourceBuilder.query(new MultiMatchQueryBuilder("我是张三","user","message"));
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits hits = searchResponse.getHits();
        SearchHit[] searchHits = hits.getHits();
        for (SearchHit hit : searchHits) {
            // do something with the SearchHit

            System.out.println(hit.getSourceAsString());
        }
    }

	//最简单的添加索引数据
    public static void zz(String[] args) throws Exception{
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http")
                ));
        Map<String, Object> jsonMap = new HashMap<>();
        jsonMap.put("user", "bababa");
        jsonMap.put("postDate", new Date());
        jsonMap.put("message", "张三");
        IndexRequest request = new IndexRequest("posts")
                .id("1").source(jsonMap);
        IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
        System.out.println(indexResponse.toString());
    }

    public static void main(String[] args) throws  Exception{
        select(null);
    }
}

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
可以使用Elasticsearch的聚合(Aggregation)功能来查询多个索引并对索引名进行分组。具体实现步骤如下: 1. 首先创建一个SearchRequest对象,设置要查询索引列表和查询条件。 2. 创建一个TermsAggregationBuilder对象,设置聚合的字段为索引名,并设置其它聚合参数,如聚合大小、排序等。 3. 将TermsAggregationBuilder对象添加到SearchRequest对象中的AggregationBuilder列表中。 4. 使用RestHighLevelClient执行查询,将SearchRequest对象作为参数传入search()方法。 示例代码如下: ``` SearchRequest searchRequest = new SearchRequest("index1", "index2"); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.query(QueryBuilders.matchAllQuery()); TermsAggregationBuilder aggregationBuilder = AggregationBuilders.terms("index_names").field("_index"); searchSourceBuilder.aggregation(aggregationBuilder); searchRequest.source(searchSourceBuilder); SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT); Terms indexNames = searchResponse.getAggregations().get("index_names"); for (Terms.Bucket bucket : indexNames.getBuckets()) { String indexName = bucket.getKeyAsString(); long docCount = bucket.getDocCount(); // Do something with indexName and docCount } ``` 以上示例代码中,我们查询了两个索引index1和index2,并对它们进行了分组。最后,我们使用聚合结果中的Bucket对象获取索引名和文档数量等信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值