liyugang
3 天以前 8c24730e9a52dc2c8933e8d41d2f9651de48a231
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
import { Client } from '@elastic/elasticsearch';
import xlsx from "node-xlsx";
import * as fs from 'fs';
import * as mysql from 'mysql2';
const INDEX_NAME = 'zlib_books';
 
const client = new Client({ node: 'http://localhost:9200' });
let connection;
 
async function createIndex() {
  try {
    if (await client.indices.exists({ index: INDEX_NAME })) { return; }
    await client.indices.create({
      index: INDEX_NAME,
      body: {
        mappings: {
          properties: {
            id: { type: 'keyword' },
            zid: { type: 'keyword' },
            title: { type: 'text' },
            author: { type: 'text' },
            isbn: { type: 'text' },
            ext: { type: 'text' },
            file: { type: 'text' }
          },
        },
      }
    });
  } catch (e) {
    console.error(e);
  }
}
 
function getBooksFromExcel(excelFile) {
  const workSheets = xlsx.parse(excelFile);
  const result = [];
  for (const sheet of workSheets) {
    const books = sheet.data;
    // books.shift();
    for (const row of books) {
      const [id, isbn, title, author, ext] = row;
      result.push({ zid: `${id}`, isbn: `${isbn ?? ''}`, title: `${title ?? ''}`, author: `${author ?? ''}`, ext: `${ext}`, file: `${id}.${ext}`.toLowerCase() });
    }
  }
  return result;
}
 
let dbIdx = 0;
let pageSize = 300000;
 
function getBook100000() {
  return new Promise((resolve, reject) => {
    connection.query(
      `SELECT books.zlibrary_id id, isbn.isbn,title,Author,extension, md5_reported FROM isbn LEFT JOIN books ON books.zlibrary_id=isbn.zlibrary_id LIMIT ${dbIdx * pageSize}, ${pageSize}`,
      function (error, results, fields) {
        if (error) throw error;
        const bookList = results.map(row => ({ zid: `${row.id}`, isbn: `${row.isbn ?? ''}`, title: `${row.title ?? ''}`, author: `${row.author ?? ''}`, md5: `${row.md5_reported}`, ext: `${row.extension}`, file: `${row.id}.${row.extension}`.toLowerCase() }));
        resolve(bookList);
        dbIdx++;
      }
    );
  });
}
 
async function indexBooks() {
  // const files = [
  //   // "C:\\Users\\lyg\\Downloads\\书单z-0-100w.xlsx",
  //   // "C:\\Users\\lyg\\Downloads\\书单z-100w-200w.xlsx",
  //   // "C:\\Users\\lyg\\Downloads\\书单z-200w-300w.xlsx",
  //   // "C:\\Users\\lyg\\Downloads\\书单z-300w-400w.xlsx",
  //   "C:\\Users\\lyg\\Downloads\\书单z-400w-500w.xlsx",
  //   "C:\\Users\\lyg\\Downloads\\书单z-500w-5027926.xlsx",
  // ];
  // const bookList = [];
  // for (const file of files) {
  //   const books = getBooksFromExcel(file);
  //   books.forEach(bk => bookList.push(bk));
  // }
 
  // const bookGroups = [];
  // for (let i = 0; i < bookList.length; i += 10000) {
  //   bookGroups.push(bookList.slice(i, i + 10000));
  // }
 
  for (; ;) {
    const bookGroup = await getBook100000();
    if (!bookGroup.length) return;
    const body = bookGroup.map(book => ([{ index: { _index: INDEX_NAME, _id: book.id } }, book])).flat();
    try {
      const response = await client.bulk({ body });
      console.log(response.errors);
    } catch (e) {
      console.error(e);
    }
  }
}
 
async function importBooToEs() {
  connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'xA123456',
    database: 'fiction'
  });
  connection.connect();
  await createIndex();
  await indexBooks();
}
 
 
// const EXCEL_FILE = "D:\\书单\\【反馈客户】7月批次书单 - 已撞库.xlsx"; // 190795 libgen匹配92788本书 88920
// const EXCEL_FILE = "D:\\书单\\清单第二批0723-已撞库.xlsx"; // 79752 libgen匹配35177本书 9112
// const EXCEL_FILE = "D:\\书单\\8月\\【反馈客户】书籍_中文在线0813_已完成_2.xlsx";
// const EXCEL_FILE = "D:\\书单\\清单第二批0723-已撞库-zlib.xlsx"; // 79752 libgen匹配35177本书 9112
// const EXCEL_FILE = "D:\\书单\\【反馈客户】7月批次书单 - 已撞库-zlib.xlsx"; // 79752 libgen匹配35177本书 9112
/**
 * 
 * @param {{isbn:boolean,title:boolean}} filter 过滤条件
 * @param {{zid:number,isbn:number,title:number,author:number,md5:number,file:number}} colIdx 列索引
 * @param {string} excelFile excel
 */
async function searchBook(filter, colIdx, excelFile) {
  let books = [];
  const workSheets = xlsx.parse(excelFile);
  const header = workSheets[0].data[0];
  for (const sheet of workSheets) {
    books = books.concat(sheet.data.slice(1));
  }
  let cnt = 0;
  let bookCnt = 0;
  const promiseList = [];
  for (const book of books) {
    cnt++;
    if (cnt % 1000 == 0) {
      console.log('当前%d', cnt);
    }
    if (filter.title != null && !book[colIdx.title]) { continue; }
 
    const query = {};
    if (filter.isbn != null) {
      const isbn = `${book[colIdx.isbn]}`;
      if (isbn.includes(',')) {
        const isbns=isbn.split(',');
        query.terms = {
          isbn: isbns.map(i => i.trim().toLowerCase())
        }
      } else {
        query.term = {
          isbn: isbn.toLowerCase()
        }
      }
    } else if (filter.title != null) {
      if (book[colIdx.author] != null) {
        query.bool = {
          must: [
            {
              match: {
                title: { query: book[colIdx.title] }
              }
            },
            {
              match: {
                author: { query: book[colIdx.author] }
              }
            }
          ]
        }
      } else {
        query.match = { title: book[colIdx.title] }
      }
    } else if (filter.zid != null) {
      query.term = {
        zid: book[colIdx.zid]
      };
    }
 
    const promise = client.search({
      index: INDEX_NAME,
      size: 1,
      query
    }).then(resp => {
      if (resp.hits.total.value == 0) { return; }
      // if ((resp.hits.max_score ?? 0) < 30) {
      //   return;
      // }
      if (colIdx.zid != null) {
        book[colIdx.zid] = resp.hits.hits[0]?._source?.zid;
      }
      if (colIdx.file) {
        book[colIdx.file] = resp.hits.hits[0]?._source?.file;
      }
      if (colIdx.md5) {
        book[colIdx.md5] = resp.hits.hits[0]?._source?.md5;
      }
      bookCnt++;
      if (bookCnt % 1000 == 0) {
        console.log('已匹配:%s', bookCnt);
      }
    });
    promiseList.push(promise);
    if (promiseList.length >= 20) {
      await Promise.all(promiseList);
      promiseList.length = 0;
    }
  }
  if (promiseList.length) {
    await Promise.all(promiseList);
  }
 
  console.log(`已匹配:${bookCnt}`);
  saveToExcel(books, header, colIdx, excelFile);
}
 
async function saveToExcel(books, header, colIdx, excelFile) {
  // const libgenIds = fs.readFileSync("D:\\书单\\已下载libgen_id.txt", 'utf8').split('\n');
  // const libgenIdMap = new Map();
  // libgenIds.forEach(id => libgenIdMap.set(id, true));
 
  const data =
    books.filter(book => book[colIdx.file]);
  console.log(data.length - 1);
  data.splice(0, 0, header);
  const sheets = [];
  for (let i = 0; i < data.length; i += 1000000) {
    sheets.push({ name: "Sheet" + (i / 1000000), data: data.slice(i, i + 1000000) });
  }
  const buffer = xlsx.build(sheets);
 
  const notMatchData = books
    .filter(book => !book[colIdx.file]);
  notMatchData.splice(0, 0, header);
  const buffer2 = xlsx.build([{ name: "Sheet1", data: notMatchData }]);
  try {
    fs.writeFileSync(`${excelFile.substring(0, excelFile.lastIndexOf('.'))}.zlib.xlsx`, buffer, (err) => { });
    fs.writeFileSync(`${excelFile.substring(0, excelFile.lastIndexOf('.'))}.zlib.nomatch.xlsx`, buffer2, (err) => { });
  } catch (e) {
    console.error(e);
  }
}
 
async function searchByIsbn(colIdx, excelFile) {
  searchBook({ isbn: true }, colIdx, excelFile);
}
 
async function searchByTitle(colIdx, excelFile) {
  searchBook({ title: true }, colIdx, excelFile);
}
async function searchByZid(colIdx, excelFile) {
  searchBook({ zid: true }, colIdx, excelFile);
}
 
function addFile2Excel() {
  const fileMap = new Map();
  fs.readFileSync("zlib-files.txt", "utf-8").split("\n").forEach(line => {
    const [id, ext] = line.split(".");
    fileMap.set(id, line);
  });
  const excelFile = "D:\\书单\\8月\\书单1-2.xlsx";
  const workSheets = xlsx.parse(excelFile);
  for (const sheet of workSheets) {
    sheet.data.slice(1).forEach(row => {
      const id = row[0];
      const file = fileMap.get(id + '');
      row[4] = file;
    });
  }
  const buffer = xlsx.build(workSheets);
  fs.writeFileSync(`${excelFile}.file.xlsx`, buffer, (err) => { });
}
 
// importBooToEs();
// searchByIsbn(
//   { isbn: 2, zid: 6, md5: 7, file: 8 },
//   "D:\\书单\\8月\\【反馈客户】书籍_中文在线0813_已完成_3.xlsx"
// );
searchByZid(
  { isbn: 3, zid: 0, md5: 4, file: 5 },
  "C:\\Users\\lyg\\Documents\\WeChat Files\\wxid_e8swvjxjvxz321\\FileStorage\\File\\2024-08\\书单-929648本.xlsx"
);
// searchByTitle(
//   { title: 0, isbn: 2, author: 3, zid: 6, md5: 7, file: 8 },
//   "D:\\书单\\8月\\【反馈客户】书籍_中文在线0813_已完成_3.xlsx"
// )
 
// addFile2Excel();