Spring整合Elasticsearch----查询方法

一、查询lookup策略

Elasticsearch模块支持所有基本的查询构建功能,如字符串查询、native搜索查询、基于条件的查询和从方法名派生的查询。

1.1 声明的查询

从方法名称派生查询并不总是足够的,并且可能导致方法名称不可读。在这种情况下,可以使用@Query注解(请参见四、使用@Query注解)。

二、创建查询

通常,Elasticsearch的查询创建机制如定义查询方法中描述的那样工作。下面是一个简短的示例,说明了Elasticsearch查询方法的含义:
例1:从方法名创建查询

interface BookRepository extends Repository<Book, String> {
  List<Book> findByNameAndPrice(String name, Integer price);
}

上面的方法名将被转换为下面的Elasticsearch json查询

{
    "query": {
        "bool" : {
            "must" : [
                { "query_string" : { "query" : "?", "fields" : [ "name" ] } },
                { "query_string" : { "query" : "?", "fields" : [ "price" ] } }
            ]
        }
    }
}

Elasticsearch支持的关键字列表如下所示。
表1:方法名称中支持的关键字

关键字例子Elasticsearch查询字符串
AndfindByNameAndPrice{ “query” : {“bool” : {“must” : [{ “query_string” : { “query” : “?”, “fields” : [ “name” ] } },{“query_string” : { “query” : “?”, “fields” : [ “price” ] } }]}}}
OrfindByNameOrPrice{“query”:{“bool”:{“should”:[{“query_string”:{“query”:“?”,“fields”:[“name”]}},{“query_string”:{“query”:“?”,“fields”:[“price”]}}]}}}
IsfindByName{“query”:{“bool”:{“must”:[{“query_string”:{“query”:“?”,“fields”:[“name”]}}]}}}
NotfindByNameNot{“query”:{“bool”:{“must_not”:[{“query_string”:{“query”:“?”,“fields”:[“name”]}}]}}}
BetweenfindByPriceBetween{“query”:{“bool”:{“must”:[{“range”:{“price”:{“from”:“?”,“to”:“?”,“include_lower”:true,“include_upper”:true}}}]}}}
LessThanfindByPriceLessThan{“query”:{“bool”:{“must”:[{“range”:{“price”:{“from”:null,“to”:“?”,“include_lower”:true,“include_upper”:false}}}]}}}
LessThanEqualfindByPriceLessThanEqual{“query”:{“bool”:{“must”:[{“range”:{“price”:{“from”:null,“to”:“?”,“include_lower”:true,“include_upper”:true}}}]}}}
GreaterThanfindByPriceGreaterThan{“query”:{“bool”:{“must”:[{“range”:{“price”:{“from”:“?”,“to”:null,“include_lower”:false,“include_upper”:true}}}]}}}
GreaterThanEqualfindByPriceGreaterThanEqual{“query”:{“bool”:{“must”:[{“range”:{“price”:{“from”:“?”,“to”:null,“include_lower”:true,“include_upper”:true}}}]}}}
BeforefindByPriceBefore{“query”:{“bool”:{“must”:[{“range”:{“price”:{“from”:null,“to”:“?”,“include_lower”:true,“include_upper”:true}}}]}}}
AfterfindByPriceAfter{“query”:{“bool”:{“must”:[{“range”:{“price”:{“from”:“?”,“to”:null,“include_lower”:true,“include_upper”:true}}}]}}}
LikefindByNameLike{“query”:{“bool”:{“must”:[{“query_string”:{“query”:“?*”,“fields”:[“name”]},“analyze_wildcard”:true}]}}}
StartingWithfindByNameStartingWith{“query”:{“bool”:{“must”:[{“query_string”:{“query”:“?*”,“fields”:[“name”]},“analyze_wildcard”:true}]}}}
EndingWithfindByNameEndingWith{“query”:{“bool”:{“must”:[{“query_string”:{“query”:“*?”,“fields”:[“name”]},“analyze_wildcard”:true}]}}}
Contains/ContainingfindByNameContaining{“query”:{“bool”:{“must”:[{“query_string”:{“query”:“?”,“fields”:[“name”]},“analyze_wildcard”:true}]}}}
In (when annotated as FieldType.Keyword)findByNameIn(Collection<String> names){“query”:{“bool”:{“must”:[{“bool”:{“must”:[{“terms”:{“name”:[“?”,“?”]}}]}}]}}}
InfindByNameIn(Collection<String> names){ “query”: {“bool”: {“must”: [{“query_string”:{“query”: “”?" “?”", “fields”: [“name”]}}]}}}
NotIn (when annotated as FieldType.Keyword)findByNameNotIn(Collection<String> names){“query”:{“bool”:{“must”:[{“bool”:{“must_not”:[{“terms”:{“name”:[“?”,“?”]}}]}}]}}}
NotInfindByNameNotIn(Collectionnames){“query”: {“bool”: {“must”: [{“query_string”: {“query”: “NOT(”?" “?”)", “fields”: [“name”]}}]}}}
TruefindByAvailableTrue{“query”:{“bool”:{“must”:[{“query_string”:{“query”:“true”,“fields”:[“available”]}}]}}}
FalsefindByAvailableFalse{“query”:{“bool”:{“must”:[{“query_string”:{“query”:“false”,“fields”:[“available”]}}]}}}
OrderByfindByAvailableTrueOrderByNameDesc{“query”:{“bool”:{“must”:[{“query_string”:{“query”:“true”,“fields”:[“available”]}}]}},“sort”:[{“name”:{“order”:“desc”}}]}
ExistsfindByNameExists{“query”:{“bool”:{“must”:[{“exists”:{“field”:“name”}}]}}}
IsNullfindByNameIsNull{“query”:{“bool”:{“must_not”:[{“exists”:{“field”:“name”}}]}}}
IsNotNullfindByNameIsNotNull{“query”:{“bool”:{“must”:[{“exists”:{“field”:“name”}}]}}}
IsEmptyfindByNameIsEmpty{“query”:{“bool”:{“must”:[{“bool”:{“must”:[{“exists”:{“field”:“name”}}],“must_not”:[{“wildcard”:{“name”:{“wildcard”:“*”}}}]}}]}}}
IsNotEmptyfindByNameIsNotEmpty{“query”:{“bool”:{“must”:[{“wildcard”:{“name”:{“wildcard”:“*”}}}]}}}

不支持使用GeoJson参数构建Geo-shape查询的方法名。如果您需要在存储库中拥有这样的函数,请在自定义存储库实现中使用ElasticsearchOperations和CriteriaQuery。

三、方法返回类型

存储库方法可以定义为具有以下返回类型以返回多个元素:

  • List<T>
  • Stream<T>
  • SearchHits<T>
  • List<SearchHit<T>>
  • Stream<SearchHit<T>>
  • SearchPage<T>

四、使用@Query注解

例2:使用@Query注解在方法上声明query
传递给该方法的参数可以插入到查询字符串中的占位符中。第一个、第二个、第三个参数的占位符形式为?0、?1、?2等。

interface BookRepository extends ElasticsearchRepository<Book, String> {
    @Query("{\"match\": {\"name\": {\"query\": \"?0\"}}}")
    Page<Book> findByName(String name,Pageable pageable);
}

设置为注解参数的String必须是一个有效的Elasticsearch JSON查询。它将作为查询元素的值发送给Elasticsearch;例如,如果使用参数John调用函数,它将产生以下查询体:

{
  "query": {
    "match": {
      "name": {
        "query": "John"
      }
    }
  }
}

例3:使用Collection参数的方法上的@Query注解

@Query("{\"ids\": {\"values\": ?0 }}")
List<SampleEntity> getByIds(Collection<String> ids);

像上面这样的存储库方法将进行ID查询以返回所有匹配的文档。因此,调用List为[“id1”、“id2”、“id3”]的方法将生成查询体

{
  "query": {
    "ids": {
      "values": ["id1", "id2", "id3"]
    }
  }
}
  • 10
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,关于 Spring Boot Starter Data 整合 Elasticsearch,可以按照以下步骤进行: 1. 在 pom.xml 文件中添加 Elasticsearch 的依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> ``` 2. 在 application.properties 文件中配置 Elasticsearch 的连接信息: ```properties spring.data.elasticsearch.cluster-nodes=localhost:9300 spring.data.elasticsearch.cluster-name=my-application ``` 其中,cluster-nodes 是 Elasticsearch 集群节点的地址,cluster-name 是集群名称。 3. 创建一个 ElasticsearchRepository 接口来定义 Elasticsearch 的操作: ```java public interface BookRepository extends ElasticsearchRepository<Book, String> { } ``` 其中,Book 是实体类,String 是实体类主键的数据类型。 4. 在需要使用 Elasticsearch 的地方注入 ElasticsearchRepository 接口,并使用它进行数据操作: ```java @Autowired private BookRepository bookRepository; public void saveBook(Book book) { bookRepository.save(book); } public List<Book> findBooksByAuthor(String author) { return bookRepository.findByAuthor(author); } ``` 这里的 save 方法是保存数据,findByAuthor 方法是按照作者查询数据。 以上就是 Spring Boot Starter Data 整合 Elasticsearch 的基本步骤。需要注意的是,这里使用的是 ElasticsearchRepository 接口,它提供了一些常用的操作方法,如果需要更多的操作,可以使用 ElasticsearchTemplate 类来进行操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值