欢迎投稿

今日深度:

ElasticSearch搜索引擎的使用整合SpringMVC,

ElasticSearch搜索引擎的使用整合SpringMVC,


下载、安装、工具

下载并加压:ElasticSearch,来自 how2j

中文分词器:http://how2j.cn/frontdownload?bean.id=1696

执行安装分词器:(从github安装)

elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v6.2.2/elasticsearch-analysis-ik-6.2.2.zip

从本地安装:

cd 安装路径

elasticsearch-plugin install zip路径/elasticsearch-analysis-ik-6.2.2.zip

工具:kibana

搭建

SpringMvc部分参照文章:ssm maven 工程目录以及环境搭建

pom包:


    
      org.elasticsearch.client
      elasticsearch-rest-high-level-client
      6.3.2
    

工具类:

public class ElasticUtils {

    // 相当于大乐透追加倍投多少钱名称(数据量小)
    public static String indexName = "shose";



    // 初始化api客户端
    public static RestHighLevelClient client = new RestHighLevelClient(
            RestClient.builder(
                    new HttpHost("localhost", 9200, "http")
            ));

    // 关键字搜索 指定匹配类型
    public static List<>> search(String type,String fieldName, String keyword, int start, int count) throws IOException {


        SearchRequest searchRequest = new SearchRequest(indexName);

        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //关键字匹配对应字段
        MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder(fieldName, keyword);
        //模糊匹配
        matchQueryBuilder.fuzziness(Fuzziness.AUTO);
        sourceBuilder.query(matchQueryBuilder);
        //第几页
        sourceBuilder.from(start);
        //第几条
        sourceBuilder.size(count);

        searchRequest.source(sourceBuilder);
        searchRequest.types(type);
        //匹配度从高到低
        sourceBuilder.sort(new ScoreSortBuilder().order(SortOrder.DESC));

        SearchResponse searchResponse = client.search(searchRequest);

        SearchHits hits = searchResponse.getHits();

        List<>> matchRsult = new LinkedList<>>();

        for (SearchHit hit : hits.getHits())
        {
            matchRsult.add(hit.getSourceAsMap());
        }
        return matchRsult;
    }
    //删除指定类型
    public static void deleteDocument(Object object) throws IOException {
        if(object instanceof Product){
            DeleteRequest deleteRequest = new DeleteRequest (indexName,"product", ((Product) object).getId());
            System.out.println("已经从ElasticSearch服务器上删除id="+((Product) object).getId()+"的product文档");
            client.delete(deleteRequest);
        }
    }
    // 获得指定type指定id的数据 json
    public static Map getDocument(String type,String id) throws IOException {
        // TODO Auto-generated method stub
        GetRequest request = new GetRequest(
                indexName,
                type,
                id);

        GetResponse response = client.get(request);

        if(!response.isExists()){
            System.out.println("检查到服务器上 "+type+" id="+id+ "的文档不存在");
            return null;
        }
        else{
            String source = response.getSourceAsString();
            System.out.print("获取到服务器上 "+type+" id="+id+ "的文档内容是:");
            System.out.println(source);
            return response.getSourceAsMap();
        }
    }
    // 插入指定type,数据
    public static void addDocument(Object object) throws IOException {
        Map jsonMap = new HashMap<>();
        if(object instanceof Product){
            jsonMap.put("id", ((Product)object).getId());
            jsonMap.put("name", ((Product)object).getName());
            jsonMap.put("price", ((Product)object).getPrice());
            jsonMap.put("detail", ((Product)object).getDetail());
            IndexRequest indexRequest = new IndexRequest(indexName, "product", ((Product)object).getId())
                    .source(jsonMap);
            client.index(indexRequest);
            System.out.println("已经向ElasticSearch服务器增加Product:"+object);
        }

    }
    // 更新数据
    public static void updateDocument(Object object) throws IOException {

        if(object instanceof Product){
            UpdateRequest updateRequest = new UpdateRequest (indexName, "product", ((Product) object).getId())
                    .doc("name",((Product) object).getId())
                    .doc("price",((Product) object).getPrice())
                    .doc("detail",((Product) object).getDetail());
            client.update(updateRequest);
            System.out.println("已经在ElasticSearch服务器修改产品为:"+object);
        }


    }
    private static boolean checkExistIndex(String indexName) throws IOException {
        boolean result =true;
        try {

            OpenIndexRequest openIndexRequest = new OpenIndexRequest(indexName);
            client.indices().open(openIndexRequest).isAcknowledged();

        } catch (ElasticsearchStatusException ex) {
            String m = "Elasticsearch exception [type=index_not_found_exception, reason=no such index]";
            if (m.equals(ex.getMessage())) {
                result = false;
            }
        }
        if(result)
            System.out.println("索引:" +indexName + " 是存在的");
        else
            System.out.println("索引:" +indexName + " 不存在");

        return result;

    }

    private static void deleteIndex(String indexName) throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest(indexName);
        client.indices().delete(request);
        System.out.println("删除了索引:"+indexName);

    }

    private static void createIndex(String indexName) throws IOException {
        // TODO Auto-generated method stub
        CreateIndexRequest request = new CreateIndexRequest(indexName);
        client.indices().create(request);
        System.out.println("创建了索引:"+indexName);
    }

    // 批量插入
//    private static void batchInsert(List products) throws IOException {
//        // TODO Auto-generated method stub
//        BulkRequest request = new BulkRequest();
//
//        for (Product product : products) {
//            Map m  = product.toMap();
//            IndexRequest indexRequest= new IndexRequest(indexName, "product", String.valueOf(product.getId())).source(m);
//            request.add(indexRequest);
//        }
//
//        client.bulk(request);
//        System.out.println("批量插入完成");
//    }
    public static String getIndexName() {
        return indexName;
    }

    public static void setIndexName(String indexName) {
        ElasticUtils.indexName = indexName;
    }

    public static RestHighLevelClient getClient() {
        return client;
    }

    public static void setClient(RestHighLevelClient client) {
        ElasticUtils.client = client;
    }

}

实体类:

Controller:

@Controller
public class ElasticController {

    @Autowired
    private ElasticService elasticService;

    @RequestMapping(value = "product",method = RequestMethod.POST)
    @ResponseBody
    public Message addProduct(
            @RequestParam(name = "id")String id,
            @RequestParam(name = "name")String name,
            @RequestParam(name = "price")String price,
            @RequestParam(name = "detail")String detail){
        return elasticService.addProduct(new Product(id,name,price,detail));
    }

    @RequestMapping(value = "product",method = RequestMethod.DELETE)
    @ResponseBody
    public Message delProduct(
            @RequestParam(name = "id")String id){
        return elasticService.delProduct(id);
    }

    @RequestMapping(value = "product",method = RequestMethod.PUT)
    @ResponseBody
    public Message updateProduct(
            @RequestParam(name = "id")String id,
            @RequestParam(name = "name")String name,
            @RequestParam(name = "price")String price,
            @RequestParam(name = "detail")String detail){
        return elasticService.updateProduct(new Product(id,name,price,detail));
    }

    @RequestMapping(value = "product",method = RequestMethod.GET)
    @ResponseBody
    public Message searchProduct(
            @RequestParam(name = "fieldName",required = false)String fieldName,
            @RequestParam(name = "name",required = false)String name,
            @RequestParam(name = "start",required = false)Integer start,
            @RequestParam(name = "count",required = false)Integer count,
            @RequestParam(name = "id",required = false)String id){
        if(id != null){
            return elasticService.getProduct(id);
        }else {
            return elasticService.searchProduct(fieldName,name,start,count);
        }
    }

}

Service

@Service
public class ElasticServiceImpl implements ElasticService {


    @Override
    public Message addProduct(Product product) {
        try {
            ElasticUtils.addDocument(product);
        } catch (IOException e) {
            e.printStackTrace();
            return new Message("500",null);
        }
        return new Message("200",null);
    }

    @Override
    public Message delProduct(String id) {
        Product product = new Product();
        product.setId(id);
        try {
            ElasticUtils.deleteDocument(product);
        } catch (IOException e) {
            e.printStackTrace();
            return new Message("500",null);
        }
        return new Message("200",null);
    }

    @Override
    public Message getProduct(String id)  {
        try {
            return new Message("200",ElasticUtils.getDocument("product",id));
        } catch (IOException e) {
            e.printStackTrace();
            return new Message("500",null);
        }
    }

    @Override
    public Message searchProduct(String fieldName,String keyword,int start,int count) {
        try {
            return new Message("200",ElasticUtils.search("product",fieldName,keyword,start,count));
        } catch (IOException e) {
            e.printStackTrace();
            return new Message("500",null);
        }
    }

    @Override
    public Message updateProduct(Product product) {
        try {
            ElasticUtils.updateDocument(product);
        } catch (IOException e) {
            e.printStackTrace();
            return new Message("500",null);
        }
        return new Message("200",null);
    }
}

测试

添加一个product:成功

通过id查询product类型的数据:成功

模糊搜索数据:

删除数据:

再次查询:没有匹配数据

?更多功能有待测试?

www.htsjk.Com true http://www.htsjk.com/Elasticsearch/36086.html NewsArticle ElasticSearch搜索引擎的使用整合SpringMVC, 下载、安装、工具 下载并加压:ElasticSearch,来自 how2j 中文分词器:http://how2j.cn/frontdownload?bean.id=1696 执行安装分词器:(从github安装) elastics...
相关文章
    暂无相关文章
评论暂时关闭