鸿蒙OS 融合搜索开发指导

2020-09-18 17:51 更新

场景介绍

索引源应用,一般为有持久化数据的应用,可以通过融合搜索接口为其应用数据建立索引,并配置全局搜索可搜索实体,帮助用户通过全局搜索应用查找本应用内的数据。应用本身也提供搜索框时,也可直接在应用内部通过融合搜索接口实现全文搜索功能。

接口说明

HarmonyOS 中的融合搜索为开发者提供以下几种能力,详见API参考。

类名 接口名 描述
SearchAbility public List<IndexData> insert(String groupId, String bundleName, List<IndexData> indexDataList) 索引插入
public List<IndexData> update(String groupId, String bundleName, List<IndexData> indexDataList) 索引更新
public List<IndexData> delete(String groupId, String bundleName, List<IndexData> indexDataList) 索引删除
SearchSession public int getSearchHitCount(String queryJsonStr) 搜索命中结果数量
public List<IndexData> search(String queryJsonStr, int start, int limit) 分页搜索
public List<Recommendation> groupSearch(String queryJsonStr, int groupLimit) 分组搜索

开发步骤

实例化 SearchAbility,连接融合搜索服务。

  1. SearchAbility searchAbility = new SearchAbility(context);
  2. CountDownLatch lock = new CountDownLatch(1);
  3. // 连接服务
  4. searchAbility.connect(new ServiceConnectCallback() {
  5. @Override
  6. public void onConnect() {
  7. lock.countDown();
  8. }
  9. @Override
  10. public void onDisconnect() {
  11. }
  12. });
  13. // 等待回调,最长等待时间可自定义
  14. lock.await(3000, TimeUnit.MILLISECONDS);
  15. // 连接失败可重试

设置索引属性。

  1. // 构造索引属性
  2. List<IndexForm> indexFormList = new ArrayList<>();
  3. IndexForm primaryKey = new IndexForm("id", IndexType.NO_ANALYZED, true, true, false); // 主键,不分词
  4. indexFormList.add(primaryKey);
  5. IndexForm title = new IndexForm("title", IndexType.ANALYZED, false, true, true); // 分词
  6. indexFormList.add(title);
  7. IndexForm tagType = new IndexForm("tag_type", IndexType.SORTED, false, true, false); // 分词,同时支持排序、分组
  8. indexFormList.add(tagType);
  9. IndexForm ocrText = new IndexForm("ocr_text", IndexType.SORTED_NO_ANALYZED, false, true, false); // 支持排序、分组,不分词,所以也支持范围搜索
  10. indexFormList.add(ocrText);
  11. IndexForm dateTaken = new IndexForm("datetaken", IndexType.LONG, false, true, false); // 支持排序和范围查询
  12. indexFormList.add(dateTaken);
  13. IndexForm bucketId = new IndexForm("bucket_id", IndexType.INTEGER, false, true, false); // 支持排序和范围查询
  14. indexFormList.add(bucketId);
  15. IndexForm latitude = new IndexForm("latitude", IndexType.FLOAT, false, true, false); // 支持范围搜索
  16. indexFormList.add(latitude);
  17. IndexForm longitude = new IndexForm("longitude", IndexType.DOUBLE, false, true, false); // 支持范围搜索
  18. indexFormList.add(longitude);
  19. // 设置索引属性
  20. int result = searchAbility.setIndexForm(bundleName, 1, indexFormList);
  21. // 设置失败可重试

插入索引。

  1. // 构建索引数据List<IndexData> indexDataList = new ArrayList<>();for (int i = 0; i < 5; i++) { IndexData indexData = new IndexData(); indexData.put("id", "id" + i); indexData.put("title", "title" + i); indexData.put("tag_type", "tag_type" + i); indexData.put("ocr_text", "ocr_text" + i); indexData.put("dat// 构建索引数据
  2. List<IndexData> indexDataList = new ArrayList<>();
  3. for (int i = 0; i < 5; i++) {
  4. IndexData indexData = new IndexData();
  5. indexData.put("id", "id" + i);
  6. indexData.put("title", "title" + i);
  7. indexData.put("tag_type", "tag_type" + i);
  8. indexData.put("ocr_text", "ocr_text" + i);
  9. indexData.put("datetaken", System.currentTimeMillis());
  10. indexData.put("bucket_id", i);
  11. indexData.put("latitude", i / 5.0 * 180);
  12. indexData.put("longitude", i / 5.0 * 360);
  13. indexDataList.add(indexData);
  14. }
  15. // 插入索引
  16. List<IndexData> failedList = searchAbility.insert(SearchParameter.DEFAULT_GROUP, bundleName, indexDataList);
  17. // 失败的记录可以持久化,稍后重试etaken", System.currentTimeMillis()); indexData.put("bucket_id", i); indexData.put("latitude", i / 5.0 * 180); indexData.put("longitude", i / 5.0 * 360); indexDataList.add(indexData);}// 插入索引List<IndexData> failedList = searchAbility.insert(SearchParameter.DEFAULT_GROUP, bundleName, indexDataList);// 失败的记录可以持久化,稍后重试

构建查询。

  1. // 构建查询
  2. JSONObject jsonObject = new JSONObject();
  3. // SearchParameter.QUERY对应用户输入,搜索域应该都是分词的
  4. // 这里假设用户输入是“天空”,要在"title", "tag_type"这两个域上发起搜索
  5. JSONObject query = new JSONObject();
  6. query.put("天空", new JSONArray(Arrays.asList("title", "tag_type")));
  7. jsonObject.put(SearchParameter.QUERY, query);
  8. // SearchParameter.FILTER_CONDITION对应的JSONArray里可以添加搜索条件
  9. // 对于索引库里的一条索引,JSONArray下的每个JSONObject指定的条件都必须满足才会命中,JSONObject里的条件组合满足其中一个,这个JSONObject指定的条件即可满足
  10. JSONArray filterCondition = new JSONArray();
  11. // 第一个条件,一个域上可能取多个值
  12. JSONObject filter1 = new JSONObject();
  13. filter1.put("bucket_id", new JSONArray(Arrays.asList(0, 1, 2))); // 一条索引在"bucket_id"的取值为0或1或2就能命中
  14. filter1.put("id", new JSONArray(Arrays.asList(0, 1))); // 或者在"id"的取值为0或者1也可以命中
  15. filterCondition.put(filter1);
  16. // 第二个条件,一个值可能在多个域上命中
  17. JSONObject filter2 = new JSONObject();
  18. filter2.put("tag_type", new JSONArray(Arrays.asList("白云")));
  19. filter2.put("ocr_text", new JSONArray(Arrays.asList("白云"))); // 一条索引只要在"tag_type"或者"ocr_text"上命中"白云"就能命中
  20. filterCondition.put(filter2);
  21. jsonObject.put(SearchParameter.FILTER_CONDITION, filterCondition); // 一条索引要同时满足第一和第二个条件才能命中
  22. // SearchParameter.DEVICE_ID_LIST对应设备ID,匹配指定设备ID的索引才会命中
  23. JSONObject deviceId = new JSONObject();
  24. deviceId.put("device_id", new JSONArray(Arrays.asList("localDeviceId")));
  25. jsonObject.put(SearchParameter.DEVICE_ID_LIST, deviceId);
  26. // 可以在支持范围搜索的索引域上发起范围搜索,一条索引在指定域的值都落在对应的指定范围才会命中
  27. JSONObject latitude = new JSONObject();
  28. latitude.put(SearchParameter.LOWER, -40.0f); // inclusive
  29. latitude.put(SearchParameter.UPPER, 40.0.f); // inclusive
  30. jsonObject.put("latitude", latitude); // 纬度必须在[-40.0f, 40.0f]
  31. JSONObject longitude new JSONObject();
  32. longitude.put(SearchParameter.LOWER, -90.0); // inclusive
  33. longitude.put(SearchParameter.UPPER, 90.0); // inclusive
  34. jsonObject.put("longitude", longitude); // 经度必须在[-90.0, 90.0]
  35. // SearchParameter.ORDER_BY对应搜索结果的排序,排序字段通过SearchParameter.ASC和SearchParameter.DESC
  36. // 指定搜索结果在这个字段上按照升序、降序排序,这里填充字段的顺序是重要的,比如这里两个索引之间会先在"id"
  37. // 字段上升序排序,只有在"id"上相同时,才会继续在"datetaken"上降序排序,以此类推
  38. JSONObject order = new JSONObject();
  39. order.put("id", SearchParameter.ASC);
  40. order.put("title", SearchParameter.ASC);
  41. order.put("datetaken", SearchParameter.DESC);
  42. jsonObject.put(SearchParameter.ORDER_BY, order);
  43. // SearchParameter.GROUP_FIELD_LIST对应的群组搜索的域,调用gruopSearch接口需要指定
  44. jsonObject.put(SearchParameter.GROUP_FIELD_LIST, new JSONArray(Arrays.asList("tag_type", "ocr_text")));
  45. // 得到查询字符串
  46. String queryJsonStr = jsonObject.toString();
  47. // 构建的json字符串如下:
  48. /**
  49. {
  50. "SearchParameter.QUERY": {
  51. "天空": [
  52. "title",
  53. "tag_type"
  54. ]
  55. },
  56. "SearchParameter.FILTER_CONDITION": [
  57. {
  58. "bucket_id": [
  59. 0,
  60. 1,
  61. 2
  62. ],
  63. "id": [
  64. 0,
  65. 1
  66. ]
  67. },
  68. {
  69. "tag_type": [
  70. "白云"
  71. ],
  72. "ocr_text": [
  73. "白云"
  74. ]
  75. }
  76. ],
  77. "SearchParameter.DEVICE_ID_LIST": {
  78. "device_id": [
  79. "localDeviceId"
  80. ]
  81. },
  82. "latitude": {
  83. "SearchParameter.LOWER": -40.0,
  84. "SearchParameter.UPPER": 40.0
  85. },
  86. "longitude": {
  87. "SearchParameter.LOWER": -90.0,
  88. "SearchParameter.UPPER": 90.0
  89. },
  90. "SearchParameter.ORDER_BY": {
  91. "id": "ASC",
  92. "title": "ASC",
  93. "datetaken": "DESC"
  94. },
  95. "SearchParameter.GROUP_FIELD_LIST": [
  96. "tag_type",
  97. "ocr_text"
  98. ]
  99. }
  100. **/

开始搜索会话,发起搜索。

  1. // 开始搜索会话
  2. SearchSession searchSession = searchAbility.beginSearch(SearchParameter.DEFAULT_GROUP, bundleName);
  3. if (searchSession == null) {
  4. return;
  5. }
  6. try {
  7. int hit = searchSession.getSearchHitCount(queryJsonStr); // 获取总命中数
  8. int batch = 50; // 每页最多返回50个结果
  9. for (int i = 0; i < hit; i += batch) {
  10. List<IndexData> result = searchSession.search(queryJsonStr, i, batch);
  11. ...
  12. // 处理IndexData
  13. }
  14. int groupLimit = 10; // 每个分组域上最多返回10个分组结果
  15. List<Recommendation> result = searchSession.groupSearch(queryJsonStr, groupLimit);
  16. // 处理Recommendation
  17. for (Recommendation recommendation : result) {
  18. HiLog.info(LABEL, "field: %{public}s, value: %{public}s, count: %{public}d", recommedation.getField(), recommendation.getValue(), recommendation.getCount());
  19. }
  20. } finally {
  21. // 释放资源
  22. searchAbility.endSearch(SearchParameter.DEFAULT_GROUP, bundleName, searchSession);
  23. }
以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号