如何在springboot中使用ElasticSearch查询

3vpjnl9f  于 2022-12-03  发布在  ElasticSearch
关注(0)|答案(1)|浏览(155)
GET products/_search
{
  "query": {
    "multi_match" : {
      "query":    "novel", 
      "fields": [ "description", "name","id" ,"price"] 
    }
  }
}

我想在我的spring Boot 应用程序上触发这个查询来搜索关键字searching。这是我的conreoller类,我将使用它的函数

package com.pixelTrice.elastic.search;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

@RestController
public class ElasticSearchController {

    @Autowired
    private ElasticSearchQuery elasticSearchQuery;

    @PostMapping("/createOrUpdateDocument")
    public ResponseEntity<Object> createOrUpdateDocument(@RequestBody Product product) throws IOException {
          String response = elasticSearchQuery.createOrUpdateDocument(product);
        return new ResponseEntity<>(response, HttpStatus.OK);
    }

    @GetMapping("/getDocument")
    public ResponseEntity<Object> getDocumentById(@RequestParam String productId) throws IOException {
       Product product =  elasticSearchQuery.getDocumentById(productId);
        return new ResponseEntity<>(product, HttpStatus.OK);
    }

    @DeleteMapping("/deleteDocument")
    public ResponseEntity<Object> deleteDocumentById(@RequestParam String productId) throws IOException {
        String response =  elasticSearchQuery.deleteDocumentById(productId);
        return new ResponseEntity<>(response, HttpStatus.OK);
    }

    @GetMapping("/searchDocument")
    public ResponseEntity<Object> searchAllDocument() throws IOException {
        List<Product> products = elasticSearchQuery.searchAllDocuments();
        return new ResponseEntity<>(products, HttpStatus.OK);
    }
    @GetMapping("/searching")
    public ResponseEntity<Object> searching() throws IOException{
         List<Product> products = elasticSearchQuery.searching();
         return new ResponseEntity<>(products,HttpStatus.OK);
        
    }
}

这是我的查询类,因为我想写java查询:
第一次
我在kibana上试过这个,并在“小说”上得到我想要的关键字搜索,它向我显示了我想要的结果,现在我想把这个转换成java api,但想不出我怎么能在java上写它的sysntax

eh57zj3b

eh57zj3b1#

试试这个:

SearchRequest searchRequest = new SearchRequest();
searchRequest.indices("idx_name");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

MultiMatchQueryBuilder multiMatchQueryBuilder = new MultiMatchQueryBuilder("novel")
    .field("description")
    .field("name")
    .field("id")
    .field("price");

searchSourceBuilder.query(multiMatchQueryBuilder);
searchRequest.source(searchSourceBuilder);

SearchResponse searchResponse = getClient().search(searchRequest, RequestOptions.DEFAULT);

相关问题