【问题标题】:How to use elasticsearch search query into springboot如何在spring boot中使用elasticsearch搜索查询
【发布时间】:2022-12-20 19:51:19
【问题描述】:
  GET products/_search
{
  "query": {
    "multi_match" : {
      "query":    "novel", 
      "fields": [ "description", "name","id" ,"price"] 
    }
  }
}

这个查询我想在我的 spring boot 应用程序上触发以搜索关键字搜索 这是我的 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 查询:

package com.pixelTrice.elastic.search;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.*;
import co.elastic.clients.elasticsearch.core.search.Hit;

import org.apache.lucene.queryparser.flexible.core.builders.QueryBuilder;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Repository;

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

@Repository
public class ElasticSearchQuery {

    @Autowired
    private ElasticsearchClient elasticsearchClient;

    private final String indexName = "products";


    public String createOrUpdateDocument(Product product) throws IOException {

        IndexResponse response = elasticsearchClient.index(i -> i
                .index(indexName)
                .id(product.getId())
                .document(product)
        );
        if (response.result().name().equals("Created")) {
            return new StringBuilder("Document has been successfully created.").toString();
        } else if (response.result().name().equals("Updated")) {
            return new StringBuilder("Document has been successfully updated.").toString();
        }
        return new StringBuilder("Error while performing the operation.").toString();
    }

    public Product getDocumentById(String productId) throws IOException {
        Product product = null;
        GetResponse<Product> response = elasticsearchClient.get(g -> g
                        .index(indexName)
                        .id(productId),
                Product.class
        );

        if (response.found()) {
            product = response.source();
            System.out.println("Product name " + product.getName());
        } else {
            System.out.println("Product not found");
        }

        return product;
    }

    public String deleteDocumentById(String productId) throws IOException {

        DeleteRequest request = DeleteRequest.of(d -> d.index(indexName).id(productId));

        DeleteResponse deleteResponse = elasticsearchClient.delete(request);
        if (Objects.nonNull(deleteResponse.result()) && !deleteResponse.result().name().equals("NotFound")) {
            return new StringBuilder("Product with id " + deleteResponse.id() + " has been deleted.").toString();
        }
        System.out.println("Product not found");
        return new StringBuilder("Product with id " + deleteResponse.id() + " does not exist.").toString();

    }
    public List<Product> searchAllDocuments() throws IOException {

        SearchRequest searchRequest = SearchRequest.of(s -> s.index(indexName));
        SearchResponse searchResponse = elasticsearchClient.search(searchRequest, Product.class);
        List<Hit> hits = searchResponse.hits().hits();
        List<Product> products = new ArrayList<>();
        for (Hit object : hits) {

            System.out.print(((Product) object.source()));
            products.add((Product) object.source());

        }
        return products;
    }

    public List<Product> searching() throws IOException{
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices(indexName);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        QueryBuilder cluase0 = QueryBuilders.multiMatchQuery(queryString, 
                "name",
                  "id",
                  "description",
                  "price");
        MultiMatchQueryBuilder multiMatchQueryBuilder1 = new MultiMatchQueryBuilder(queryString, "firstName", "lastName",
                  "password", "emailId", "userId", "mobileNumber");
            multiMatchQueryBuilder1.operator(Operator.AND);
            searchSourceBuilder.query(multiMatchQueryBuilder1);
         
    
}

  GET products/_search
{
  "query": {
    "multi_match" : {
      "query":    "novel", 
      "fields": [ "description", "name","id" ,"price"] 
    }
  }
}

我在 kibana 上尝试了这个,并在“novel”上搜索了我想要的关键字,它显示了我想要的结果,现在我想将它转换成 java api,但想不出如何在 java 上编写它的 sysntax

【问题讨论】:

    标签: rest elasticsearch kibana-4 elasticsearch-java-api


    【解决方案1】:

    SearchRequest searchRequest = SearchRequest.of(s -> s.index("products").from(from).size(size).query(q -> q.multiMatch( t -> t .fields("描述","名称").查询(文本))) ); SearchResponse searchResponse = elasticsearchClient.search(searchRequest, Product.class); 列表命中 = searchResponse.hits().hits(); 列出产品 = new ArrayList<>(); 对于(命中对象:命中){ // System.out.print(((Product) object.source())); 产品 p = (Product) object.source(); logger.info(p.getName()); System.out.println("这是记录器"); 产品.add(p);

    【讨论】:

    • 它在第一行显示错误 =" The constructor SearchRequest() is undefined "
    • 第 2 行错误 = 方法 indices(String) 未定义类型 SearchRequest
    • 在最后一行 ="SearchResponse 是原始类型。对泛型类型 SearchResponse<TDocument> 的引用应该被参数化"
    猜你喜欢
    • 2022-08-22
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    • 1970-01-01
    • 2017-08-15
    • 1970-01-01
    • 2017-04-02
    相关资源
    最近更新 更多