es的搜索基本操作

建立mapping映射

mapping是对索引库中文档的约束,常见的mapping属性包括:

  • type:字段数据类型,常见的简单类型有:

    • 字符串:text(可分词的文本)、keyword(精确值,例如:品牌、国家、ip地址)

    • 数值:long、integer、short、byte、double、float、

    • 布尔:boolean

    • 日期:date

    • 对象:object

  • index:是否创建索引,默认为true

  • analyzer:使用哪种分词器

  • properties:该字段的子字段

创建索引库,最关键的是mapping映射,而mapping映射要考虑的信息包括:

  • 字段名

  • 字段数据类型

  • 是否参与搜索

  • 是否需要分词

  • 如果分词,分词器是什么?

创建索引库,最关键的是mapping映射,而mapping映射要考虑的信息包括:

  • 字段名

  • 字段数据类型

  • 是否参与搜索

  • 是否需要分词

  • 如果分词,分词器是什么?

其中:

  • 字段名、字段数据类型,可以参考数据表结构的名称和类型

  • 是否参与搜索要分析业务来判断,例如图片地址,就无需参与搜索

  • 是否分词呢要看内容,内容如果是一个整体就无需分词,反之则要分词

  • 分词器我们可以统一使用ik_max_word

  • PUT /hotel
    {
      "mappings": {
        "properties": {
          "id": {
            "type": "keyword"
          },
          "name":{
            "type": "text",
            "analyzer": "ik_max_word",
            "copy_to": "all"
          },
          "address":{
            "type": "keyword",
            "index": false
          },
          "price":{
            "type": "integer"
          },
          "score":{
            "type": "integer"
          },
          "brand":{
            "type": "keyword",
            "copy_to": "all"
          },
          "city":{
            "type": "keyword",
            "copy_to": "all"
          },
          "starName":{
            "type": "keyword"
          },
          "business":{
            "type": "keyword"
          },
          "location":{
            "type": "geo_point"
          },
          "pic":{
            "type": "keyword",
            "index": false
          },
          "all":{
            "type": "text",
            "analyzer": "ik_max_word"
          }
        }
      }
    }

 其中有一个细节 coyp_to是将这个拷贝的all中 后面会用到 到时候再解释

2.批量导入文档

@SpringBootTest
class HotelDemoApplicationTests {

    @Autowired
    private IHotelService hotelService;
    @Autowired
    private RestHighLevelClient client;

    @Test
    public void test() throws IOException {
        //批量查询酒店数据
        List<Hotel> list = hotelService.list();
        //1.创建Request对象
        BulkRequest request =new BulkRequest();
        list.forEach(a->{ 用流拷贝
            // 2.1.转换为文档类型HotelDoc
            HotelDoc hotelDoc = new HotelDoc(a);
            // 2.2.创建新增文档的Request对象
            request.add(new IndexRequest("hotel")//对象名称
                    .id(hotelDoc.getId().toString())
                    .source(JSON.toJSONString(hotelDoc), XContentType.JSON));
        });
         // 3.发送请求
        client.bulk(request, RequestOptions.DEFAULT);
    }

    @BeforeEach //初始化客户端
    void setUp() {
        HttpHost host=HttpHost.create("http://192.168.19.128:9200");
        RestClientBuilder builder= RestClient.builder(host);
        client=new RestHighLevelClient(builder);
    }

    @AfterEach//关流
    void tearDown() throws IOException {
        client.close();
    }
}

将mysql中的数据导入es中 

es搜索命令

在启动类下 将RestHighLevelClient注册到Spring中作为一个Bean 

注意:其中的ip是你的es的ip和端口记得改!!!!

@Bean //将客户端交给spring管理
public RestHighLevelClient client(){
    return  new RestHighLevelClient(RestClient.builder(
        HttpHost.create("http://192.168.150.101:9200")
    ));
}

返回值的实体类

package cn.itcast.hotel.pojo;

import lombok.Data;

import java.util.List;

@Data
public class PageResult {
    private Long total;
    private List<HotelDoc> hotels;

    public PageResult() {
    }

    public PageResult(Long total, List<HotelDoc> hotels) {
        this.total = total;
        this.hotels = hotels;
    }
}

 接受数据的实体类

package cn.itcast.hotel.pojo;

import lombok.Data;

@Data
public class RequestParams {
    private String key;
    private Integer page;
    private Integer size;
    private String sortBy;
}

基础的查询  

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Resource
    private HotelMapper hotelMapper;

    @Resource
    private RestHighLevelClient client;

    @Override
    public PageResult search(RequestParams params) throws IOException {
        //准备Request
        SearchRequest request = new SearchRequest("hotel");//操作的数组
        //准备DSL 
        String key = params.getKey();
        if (key!=null&&key!="") { //判断key是否有值 如果有就按搜索框内容搜索
            //Query
            request.source()
                    .query(QueryBuilders.matchQuery("all", key));
        }else { //如果没有值 则查询所有
            request.source()
                    .query(QueryBuilders.matchAllQuery());
        }
        //发送请求
        SearchResponse search = client.search(request, RequestOptions.DEFAULT);
        SearchHits searchHits = search.getHits();
        PageResult pageResult = new PageResult();
        pageResult.setTotal(searchHits.getTotalHits().value);//将查询到的所有条数返回
        SearchHit[] hits = searchHits.getHits();
        ArrayList<HotelDoc> list = new ArrayList<>();
        for (SearchHit hit : hits) {//将搜索的数据进行封装
            // 获取文档source
            String json = hit.getSourceAsString();
            // 反序列化                            将json数据转换为HotelDoc格式
            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
            // 放入集合
            list.add(hotelDoc);
        }
        pageResult.setHotels(list);
        // 4.4.封装返回
        return  pageResult;
    }

 这个只是基础版本 只能做基本的输入框的查询和全部查询

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Elasticsearch是一个开源的分布式搜索和分析引擎,它可以用于存储、搜索和分析大量的数据。以下是一些Elasticsearch基本操作: 1. 安装和启动Elasticsearch:首先,你需要从Elasticsearch官方网站下载和安装Elasticsearch。安装完成后,你可以使用命令行或者图形界面来启动Elasticsearch。 2. 创建索引:在Elasticsearch中,数据存储在索引中。你可以使用PUT请求来创建一个新的索引。例如,使用curl命令可以发送以下请求来创建一个名为"my_index"的索引: ``` curl -XPUT 'localhost:9200/my_index' ``` 3. 添加文档:一旦索引创建好了,你可以使用POST请求来向索引中添加文档。文档是以JSON格式表示的数据。以下是向名为"my_index"的索引添加一个文档的示例请求: ``` curl -XPOST 'localhost:9200/my_index/_doc' -d ' { "title": "Elasticsearch Basics", "content": "This is a basic introduction to Elasticsearch" }' ``` 4. 搜索文档:你可以使用GET请求来搜索索引中的文档。以下是一个搜索名为"my_index"的索引中包含关键字"elasticsearch"的文档的示例请求: ``` curl -XGET 'localhost:9200/my_index/_search?q=elasticsearch' ``` 5. 更新文档:使用POST请求可以更新索引中的文档。以下是更新名为"my_index"的索引中ID为1的文档的示例请求: ``` curl -XPOST 'localhost:9200/my_index/_doc/1/_update' -d ' { "doc": { "content": "This is an updated content" } }' ``` 6. 删除文档:使用DELETE请求可以删除索引中的文档。以下是删除名为"my_index"的索引中ID为1的文档的示例请求: ``` curl -XDELETE 'localhost:9200/my_index/_doc/1' ``` 这些是Elasticsearch的一些基本操作。你可以根据需要进一步探索和学习更多高级功能和API。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值