solr 查询方式

  1. web 查询

  2. springboot solr 客户端查询
  3. solr 清空数据

  4. 解决:返回类型数组类型

一、solr web查询

 查询参数

q 作为查询参数,必须传递,*:* 查询所有。如果需要查询某个字段,需要传递:字段名:字段匹配

q 查询条件,必填项
start 结果集第一条记录的偏移位置,用于分页,默认为 0
rows 返回文档的记录数,用于分页,默认为 10
sort 排序
fl 指定返回字段,多个字段用逗号或空格分隔,默认返回所有字段
wt 指定输出格式,例如xml、json等
fq 过滤查询。该参数可将查询的结果限定在某一范围,由于 Solr 会对过滤查询进行缓存,因此它可以显著提升复杂查询的效率
hl 用于设置字段的高亮显示

运算符

运算符说明
: 指定字段目标值,等同于 SQL 中的 “=” 号
? 通配符,替代任意单个字符
* 通配符,替代任意多个字符
AND 表示且,等同于 “&&”
OR 表示或,等同于 “||”
NOT 表示否
() 用于构成子查询
[] 范围查询,包含头尾
{} 范围查询,不包含头尾
+ 存在运算符,表示文档中必须存在 “+” 号后的项
- 不存在运算符,表示文档中不包含 “-” 号后的项

字段查询

如果需要查询字段等于某个值,传递字段名:字段值,如果字段值可以模糊匹配加* 即可

 查询参考:https://blog.csdn.net/magicpenta/article/details/82354106

二、spring boot  solr 客户端查询

项目结构

首先 spring pom.xml 依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.10.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>top.supoman</groupId>
    <artifactId>springboot-solr</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-solr</name>
    <description>solr demo  for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-solr</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.32</version>
        </dependency>


    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

application.yml 配置solr 服务端(服务端安装配置:https://www.cnblogs.com/baizhuang/p/13780411.html)

spring:
  application:
    name: solr
  data:
    solr:
      host: http://ip:8080/solr/computer
server:
  port: 8888

客户端控制层

@RestController
@Validated
public class SolrController {

    @Autowired
    private SolrService solrService;

    @GetMapping("/save")
    public  List<User> save() throws Exception{
        return solrService.saveUser();
    }


    @GetMapping("/query")
    public SearchResult queryFromSolr(@NotBlank @RequestParam(value = "param")String param) throws Exception{
        return solrService.searchUsers(param);
    }
}

 service 以及实现 ServiceImpl

public interface SolrService {

    /**
     * 初始新增信息
     * @return
     * @throws Exception
     */
    List<User> saveUser() throws Exception;

    /**
     * 查询信息,默认不分页
     * @param queryString
     * @return
     * @throws Exception
     */
    SearchResult searchUsers(String queryString) throws Exception;

}

@Service
public class SolrServiceImpl implements SolrService {
@Autowired
private SolrClient solrClient;
private static final Integer initSize = 10;


@Override
public List<User> saveUser() throws Exception{
List<User> userList = new ArrayList<>();
for (int i = 0; i <initSize ; i++) {
User user = new User();
user.setId(UUID.randomUUID().toString());
user.setName("name"+i);
user.setSex("男"+i);
user.setAddress("第"+i+"街道".toString());
user.setHost(1100L);
userList.add(user);
}
solrClient.addBeans(userList);
solrClient.commit();
return userList;
}

@Override
public SearchResult searchUsers(String queryString) throws Exception{
queryString = new String(queryString.getBytes("ISO8859-1"), "UTF-8");
SolrQuery solrQuery = new SolrQuery();
solrQuery.setQuery(queryString);
solrQuery.setStart(0);
solrQuery.setRows(100);
solrQuery.setHighlight(true);
//设置高亮显示的域
solrQuery.addHighlightField("id");
//高亮显示前缀
solrQuery.setHighlightSimplePre("<font color='red'>");
//后缀
solrQuery.setHighlightSimplePost("</font>");
//设置默认搜索域
solrQuery.set("df", "id");

SearchResult result = searchItemDao(solrQuery);
return result;
}

public SearchResult searchItemDao(SolrQuery solrQuery) throws Exception {
SearchResult searchResult = new SearchResult();
List<User> userList = new ArrayList<User>();
//执行查询
QueryResponse response = solrClient.query(solrQuery);
if(response==null){
return searchResult;
}
//取查询结果
SolrDocumentList solrDocumentList = response.getResults();
if(solrDocumentList.isEmpty()){
return searchResult;
}
//获取高亮
Map<String, Map<String, List<String>>> map = response.getHighlighting();
searchResult.setTotal(solrDocumentList.getNumFound());

for(SolrDocument document: solrDocumentList) {
User user = new User();
List<String> list = map.get(document.get("id")).get("id");
System.out.println(document.get("id"));
System.out.println(map.get(document.get("id")));
if(!CollectionUtils.isEmpty(list)){
document.setField("highLight",list.get(0));
}
String userStr = JSONUtil.toJSON(document);
user = JSON.parseObject(userStr,User.class);

userList.add(user);
}

searchResult.setUserList(userList);
return searchResult;
}
}

对象实体:User

@Data
public class User  implements Serializable {

    private static final long serialVersionUID = -1755311179877626351L;

    @Field("id")
    private String id;

    @Field("name")
    private String name;

    @Field("sex")
    private String sex;

    @Field("address")
    private String address;

    @Field("host")
    private Long host;

    private String highLight;
}

返回 Vo对象

@Data
public class SearchResult {
    private Long total;
    private List<User> userList;
}

浏览器测试:http://localhost:8888/query?param=*da

三、solr 清空数据

在 documents 下,选择 XML 格式,documents 填写如下、

<delete><query>*:*</query></delete>
<commit/>

问题:开始返回字段是数组类型

这里往 sorl 中保存数据,结果除了 id 都是数组格式

for (int i = 0; i <10 ; i++) {
            User user = new User();
            user.setId(UUID.randomUUID().toString().replace("-",""));
            user.setName("name"+i);
            user.setSex("男");
            user.setAddress("第"+i+"街道");
            user.setHost(1100);
            userList.add(user);
        }
        try {
            solrClient.addBeans(userList);
            solrClient.commit();
        }catch (Exception e){
            e.printStackTrace();
        }

难道 id 比较特殊? 将id 改为 ids ,重新尝试。结果也保存为数据

 继续寻找原因。。。,百度搜不带,FQ google 找,一下子真有相同的问题。 

https://stackoverflow.com/questions/43879657/how-to-avoid-an-arraylist-being-set-on-a-field-annotated-bean-field-in-apache-s

 

 看到这里有一个配置: multiValue ,即一个 key 可以有单个value 与 多个value 的配置 。然后修改我的sorl 服务端配置

cd /usr/local/solr-7.7.0/solr_home/new_core/conf/

 vim managed-schema

 

这里对很多类型的字段默认的都是多值,将这里修改为 false (很多字段都需要设置),修改完,重启solr 服务端。

addBeans 接口添加新的数据,重新测试:结果正常了

参考:https://www.cnblogs.com/wdfordream/p/11377161.html

参考:https://blog.csdn.net/magicpenta/article/details/82354106

posted @ 2020-10-08 19:25  byebai95  阅读(925)  评论(0编辑  收藏  举报