当前位置:网站首页>Using streamapi assertion combination and local cache for fuzzy query (nearly 1000 times more efficient than MySQL)
Using streamapi assertion combination and local cache for fuzzy query (nearly 1000 times more efficient than MySQL)
2022-06-21 22:08:00 【Refuel every day!】
Use StreamAPI Assertion combines with local cache to do fuzzy query ( Than mysql Efficiency improvement is nearly 1000 times )
I have a need recently , Fuzzy query is required , The first thing I thought of was mysql Paging fuzzy query , However, Party A's demand is to query all data in a fuzzy way , And this fuzzy query is not easy to optimize by adding indexes
When you get this demand , I guess 2w A fuzzy query of the whole table in the database of data , It takes about 10s about :

Then I think my data volume is not large , It is difficult and almost impossible for the data in the table to exceed 100000 data , If I exist directly JVM cache Is it faster in
Do as you say , Here I use Stream in Assertion combination Fuzzy query in the same way , Unfamiliar friends can see the small examples in the appendix
Here I combine assertions based on the fields of the fuzzy query :
@Override
public List<T> likeQuery(Map<String, Object> queryMap) {
// You need to combine assertions first , Because it's an and operation , So initialize a successful assertion
Predicate<Book> p = Objects::nonNull;
for (Entry<String, Object> entry : queryMap.entrySet()) {
String k = entry.getKey();
String v = String.valueOf(entry.getValue());
Predicate<Book> p2 = null;
if (k.equalsIgnoreCase("bookName")) {
p2 = book -> book.matchName(v);
} else if (k.equalsIgnoreCase("author")) {
p2 = book -> book.matchAuthor(v);
} else if (k.equalsIgnoreCase("publishArea")) {
p2 = book -> book.matchPublishArea(v);
}
// Assertion combination
if (p2 != null){
p = p.and(p2);
}
}
// I use it myself List Caching done , All through here this obtain
return this.stream()
.filter(p)
.collect(Collectors.toList());
}
Then write the comparison logic in the entity class :
@Override
public boolean matchName(String str) {
if(this.bookName == null) return false;
return this.bookName.contains(str);
}
Then it's time to see the effect , The fuzzy query of 20000 measured data will not exceed 100ms, Generally lower , And it also includes http Requested time

adopt
ABMeasure the pressure of the interface , Total settings 1000 Threads , Make 100000 requests and record the time
100000 requests take only 31 second

see JVM Heap space occupancy
Discovery cache 2 Ten thousand data , Heap space occupation is also within a reasonable range , And GC Memory usage will be greatly reduced

The number of threads is also within a reasonable range
Fuzzy query on the front end , Very silky , There's no carton

Summary :
It is recommended not to use parallel streams to improve performance , Because there are many uncontrollable risks in the process of processing , For example, if you use thread unsafe collection classes for parallel stream operations , It is very likely to cause thread safety problems
The author suggests using fork/join The framework splits tasks manually , Ensure thread safety
appendix ,Stream Examples of assertive composite fuzzy queries
Predicate:<T>Assertion interface ; Enter an object , Return to one Boolean value , The abstract functions to be implemented areboolean test(T t)
for example :
/** * 4.Predicate<T>: Assertion interface */
@Test
public void test04(){
List<String> list= Arrays.asList("Hello"," I am Liang Fengxian ","Lambda","www","ok");
// Filter strings longer than three
System.out.println(filterStr(list,(str)->str.length()>3));
}
// demand , Add a string that meets the condition to the collection
private List<String> filterStr(List<String> list, Predicate<String> predicate) {
List<String> strList = new ArrayList<>();
for (String str : list) {
if (predicate.test(str)) {
strList.add(str);
}
}
return strList;
}
Assertion combination ( Predicate combination ), And or not
public class PredicateFunction {
// Extract common code
static List<Apple> filterApples(List<Apple> inventory, Predicate<Apple> p){
List<Apple> result = new ArrayList<>();
inventory.forEach(apple -> {
if(p.test(apple)){
result.add(apple);
}
});
return result;
}
public static void main(String[] args) {
String[] colors = {
"green","yellow","blue"};
Random r = new Random();
List<Apple> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
list.add(new Apple(colors[r.nextInt(colors.length)],r.nextInt(200)));
}
System.out.println(filterApples(list,Apple::isGreenApple));
System.out.println(filterApples(list,Apple::isHealthyApple));
// Combine two conditions
Predicate<Apple> p1 = Apple::isGreenApple;
Predicate<Apple> p2 = Apple::isHealthyApple;
// Or operations
System.out.println(filterApples(list,p1.or(p2)));
//and operation
System.out.println(filterApples(list,p1.and(p2)));
}
}
@Data
@AllArgsConstructor
class Apple{
private String color;
private int weight;
public static boolean isGreenApple(Apple apple){
return "green".equalsIgnoreCase(apple.getColor());
}
public static boolean isHealthyApple(Apple apple){
return apple.getWeight() > 150;
}
}
边栏推荐
- How to associate the QR code of wechat applet to realize the integration of two codes
- M3608 boost IC chip high efficiency 2.6a boost dc/dc converter
- In the anchoring stage of retail digitalization, more attention is paid to how to mine and transform traffic by means of Digitalization
- 你真的了解二叉树吗?(上篇)
- Tutorial on the implementation of smart contracts by solidity (4) -erc1155 contracts
- 阿里云容器服务负责人易立:云原生如何解企业降本提效难题?
- 棋牌类游戏
- 自制C#编译器
- How to use the free and easy-to-use reference management software Zotero? Can I support both Chinese and English
- The order management system realizes the unified management of enterprise order inventory
猜你喜欢

What are the authoritative websites that search English documents like CNKI?

中国工程院院士郑纬民:我对中国在下一个 IT 时代拥有一席之地很乐观

Guangdong CDC reminds: the summer vacation is coming, so the returned college students can "return home" safely
![Jerry's problem of playing songs after opening four channel EQ [chapter]](/img/ef/16d630b44df9b1c700bf8cf6acf8b2.png)
Jerry's problem of playing songs after opening four channel EQ [chapter]

先进封装,一个大周期的开始——“迎风国潮”半导体设备研讨会

Does the whole house smart home brand "zhiting technology" have an experience center?

新能源行业商业采购协同系统:赋能新能源行业采购业务,提升产业协同

Intelij idea efficient skills (I)

Revenue and profit "ebb and flow", water drops turn in pain

Fu · new life, chain · future! The conference on enabling innovation and development of urban chain technology industry was held grandly
随机推荐
杠铃策略--极稳极浪不内卷
Large language models teach agents to evolve. Openai reveals the complementary relationship between the two
From casual to boring to sick
Which small directions of cv/nlp are easy to publish papers?
ACM. Hj61 put apple ●
Qx2308 high efficiency PFM Synchronous Boost dc/dc converter
P6758 [BalticOI2013] Vim
广东疾控提醒:暑期将至,返粤大学生这样安全“归巢”
What are the conditions for MySQL to create tables
What are the authoritative websites that search English documents like CNKI?
Build Eureka server cluster
Abbkine细胞周期染色试剂盒特色和实验建议
Leetcode508- the most frequent subtree elements and - deep search
洛谷P1608 路径统计 题解
Go语言单元测试基础从入门到放弃
Data types in JS (basic)
Excuse me, which website is better for college students to check literature?
杰理之做蓝牙发射的时候,回链没有声音解决方法【篇】
What is the execution order of JS asynchronism
洛谷P1514 [NOIP2010 提高组] 引水入城 题解