1.添加POM依赖 pom.xml

<dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>6.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.plugin</groupId>
            <artifactId>transport-netty4-client</artifactId>
            <version>6.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>6.2.2</version>
            <exclusions>
                <exclusion>
                    <groupId>org.elasticsearch.plugin</groupId>
                    <artifactId>transport-netty4-client</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-commons</artifactId>
            <version>2.1.0.BUILD-SNAPSHOT</version>
        </dependency>
        <!--用来替换spring-data-elasticsearch中的jar-->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-elasticsearch</artifactId>
            <version>3.1.0.BUILD-SNAPSHOT</version>
        </dependency>

Bean实体的配置注解

以CargoBean为例 1.加这个注解,在项目启动时会自动创建index和type @Document(indexName = "oms_tf_b_cargo", type = "tf_b_cargo") 2.加入此注解使这个字段使用IK分词器 @Field(type = FieldType.Text, searchAnalyzer = "ik_max_word", analyzer = "ik_max_word") 3.在时间类型加入这个注解,可以使时间格式化 @Field(type=FieldType.Date,format = DateFormat.custom, pattern = "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis") @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8") 4.其他字段可以加@Field,如果不加会交给ES自己识别处理

@Document(indexName = "oms_tf_b_cargo", type = "tf_b_cargo")
public class CargoBean implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long cargoId;


    private Long orderId;


    @Field(type = FieldType.Text, searchAnalyzer = "ik_max_word", analyzer = "ik_max_word")
    private String cargoName;
    @Field(type=FieldType.Date,format = DateFormat.custom, pattern = "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis")
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
    private Date createdTime;
}

如果不想使用这种方式自动创建就不加@Document注解,可以自己写方法手动创建

编辑Repository继承ElasticSearchRepository接口

通过方法名创建查询和增刪改操作,类似如下:

package com.zczy.cloud.repositories;
/**
 * @Date:2018/4/27 14:00
 */

import com.zczy.cloud.entity.CargoBean;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.annotations.Query;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.data.repository.query.Param;

import java.util.List;

/**
 * @Author: 查恒
 * @Date: 2018/4/27 14:00
 * @Description:
 */
public interface CargoRepository extends ElasticsearchRepository<CargoBean, Long> {
    //根据ID查询
    CargoBean findByCargoId(long cargoId);

    List<CargoBean> findAllByOrderId(long orderId);

    //AND 语句查询
    List<CargoBean> findByCargoNameAndCargoType(String cargoName, String cargoType);


    //OR 语句查询
    List<CargoBean> findByCargoNameOrCargoType(String cargoName, Integer cargoType);

    //分页
    Page<CargoBean> findByCargoName(String cargoName, Pageable page);


    //NOT 语句查询
    Page<CargoBean> findByCargoNameNot(String cargoName, Pageable page);

    //LIKE 语句查询
    Page<CargoBean> findByCargoNameLike(String cargoName, Pageable page);

    //更新
    @Query("update CargoBean as cargo set user.cargo.cargoName = :name where cargoId = :id")
    void updateCargoBean(@Param(value = "name") String name, @Param(value = "id") Long id);
}

实现类CargoBeanServiceImpl

package com.zczy.cloud.services.impl;
/**
 * @Date:2018/4/18 14:39
 */

import com.zczy.cloud.entity.CargoBean;
import com.zczy.cloud.repositories.CargoRepository;
import com.zczy.cloud.services.CargoBeanService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: 查恒
 * @Date: 2018/4/18 14:39
 * @Description:
 */
@Service
public class CargoBeanServiceImpl implements CargoBeanService {
    private static final Logger LOGGER = LoggerFactory.getLogger(CargoBeanServiceImpl.class);
    private static final Integer pageNumber = 0;
    private static final Integer pageSize = 10;
    Pageable pageable = new PageRequest(pageNumber, pageSize);
    @Autowired
    CargoRepository cargoRepository;

    public Long saveCargo(CargoBean cargoBean) {
        CargoBean cargoResult = cargoRepository.save(cargoBean);
        return cargoResult.getCargoId();
    }


    @Override
    public CargoBean findByCargoId(long cargoId) {
        return cargoRepository.findByCargoId(cargoId);
    }

    @Override
    public List<CargoBean> findAllByOrderId(long orderId) {
        return cargoRepository.findAllByOrderId(orderId);
    }

    @Override
    public List<CargoBean> findByCargoNameAndCargoType(String cargoName, String cargoType) {
        return cargoRepository.findByCargoNameAndCargoType(cargoName, cargoType);
    }

    @Override
    public List<CargoBean> findByCargoNameOrCargoType(String cargoName, Integer cargoType) {
        return cargoRepository.findByCargoNameOrCargoType(cargoName, cargoType);
    }

    @Override
    public List<CargoBean> findByCargoName(String cargoName, Pageable page) {
        return cargoRepository.findByCargoName(cargoName, pageable).getContent();
    }

    @Override
    public List<CargoBean> findByCargoNameNot(String cargoName, Pageable page) {
        return cargoRepository.findByCargoNameNot(cargoName, pageable).getContent();
    }

    @Override
    public List<CargoBean> findByCargoNameLike(String cargoName, Pageable page) {
        return cargoRepository.findByCargoNameLike(cargoName, pageable).getContent();
    }

    @Override
    public void updateCargoBean(String name, long id) {
        cargoRepository.updateCargoBean(name,id);
    }
}

下面的表格列出了所有Elasticsearch支持的关键字

关键字 例子 Elasticsearch查询语句
And findByNameAndPrice {"bool" : {"must" : [{"field" : {"name" :"?"}},{"field" : {"price" : "?"}}]}}
Or findByNameOrPrice {"bool" : {"should" : [{"field" : {"name" :"?"}},{"field" : {"price" : "?"}}]}}
Is findByName {"bool" : {"must" :{"field" : {"name" :"?"}}}}
Not findByNameNot {"bool" : {"must_not" :{"field" : {"name" :"?"}}}}
LessThanEqual findByPriceLessThan {"bool" : {"must" :{"range" :{"price" :{"from" : null,"to" :?,"include_lower" :true,"include_upper":true}}}}}
GreaterThanEqual findByPriceGreaterThan {"bool" : {"must" :{"range" :{"price" :{"from" : ?,"to" :null,"include_lower" :true,"include_upper":true}}}}}
Before findByPriceBefore {"bool" : {"must" :{"range" : {"price" :{"from" : null,"to":?,"include_lower" :true,"include_upper" :true}}}}}
After findByPriceAfter {"bool" : {"must" :{"range" : {"price" :{"from": ?,"to" :null,"include_lower" :true,"include_upper" :true}}}}}
Like findByNameLike {"bool" : {"must" :{"field" : {"name" :{"query" : "?*","analyze_wildcard" :true}}}}}
StartingWith findByNameStartingWith {"bool" : {"must" :{"field" : {"name" :{"query" : "?*","analyze_wildcard" :true}}}}}
EndingWith findByNameEndingWith {"bool" : {"must" :{"field" : {"name" :{"query" :"*?","analyze_wildcard": true}}}}}
Contains/Containing findByNameContaining {"bool" : {"must" :{"field" : {"name" :{"query" :"?","analyze_wildcard": true}}}}}
In findByNameIn(Collectionnames) {"bool" : {"must" :{"bool" : {"should" : [{"field" : {"name" : "?"}},{"field" : {"name" : "?"}}]}}}}
NotIn findByNameNotIn(Collectionnames) {"bool" : {"must_not" :{"bool" : {"should" :{"field" : {"name" :"?"}}}}}}
Near findByStoreNear 暂不支持
True findByAvailableTrue {"bool" : {"must" :{"field" : {"available" :true}}}}
False findByAvailableFalse {"bool" : {"must" :{"field" : {"available" :false}}}}
OrderBy findByAvailableTrueOrderByNameDesc {"sort" : [{ "name" :{"order" : "desc"}}],"bool" : {"must" :{"field" : {"available" :true}}}}

其他一些操作参考 GitHub开源spring-data-elasticsearch项目

results matching ""

    No results matching ""